样式化组件 - 比 ${props => props.theme...} 更容易访问传递的主题属性

Styled components - easier way to access passed theme properties than ${props => props.theme...}

我有一个主题文件:

const theme = {
  colors: {
    dark: "#212121",
    normal: "#9E9E9E",
    light: "#EEEEEE"
  },
  typography: {
    textSize: "14px",
    subtitleSize: "28px",
    titleSize: "56px"
  }
};

export default theme;

我是他们传递到我的 App 组件的:

class App extends Component {
  render() {
    return (
      <ThemeProvider theme={theme}>
        <Provider {...this.props.stores}>
          <Router>
            <AppStyles className="app-container">
              <Header />
              <Main />
            </AppStyles>
          </Router>
        </Provider>
      </ThemeProvider>
    );
  }
}

然后像这样访问嵌套组件:

const HeaderStyles = s.div`
  .link-icon {
    font-size: ${props => props.theme.typography.subtitleSize};
  }
  .header-link > a {
    font-size: ${props => props.theme.typography.textSize};
    color: ${props => props.theme.colors.normal};
    text-decoration: none;
  }
  .header-link .active-link {
    color: ${props => props.theme.colors.dark};
  }
`;

有没有比每次都${props => props.theme.typography.textSize}访问主题道具更快捷的方法?

通常使用 JS 对象表示样式是为了保持样式的模块化和作用域——这允许您将对象导入特定组件,然后使用 'style' 属性传递对象dom 个元素。您的用例似乎违背了这个目的。如果你想使用定义为 JS 对象的样式,我建议避免上面代码块中的间接访问。或者,考虑使用 CSS 模块或直接使用 CSS。祝你好运!