我有一个主题文件:
const theme = {
colors: {
dark: "#212121",
normal: "#9E9E9E",
light: "#EEEEEE"
},
typography: {
textSize: "14px",
subtitleSize: "28px",
titleSize: "56px"
}
};
export default theme;
我将它们传递到我的应用程序组件中:
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};
}
`;
有没有比每次访问主题 Prop 时都执行 ${props => props.theme.typography.textSize}
更短的方法?
最佳答案
使用 JS 对象表示样式通常是为了保持样式模块化和范围化——这允许您将对象导入到特定组件中,然后使用 dom 元素上的“style”属性传递对象。您的用例似乎违背了这个目的。如果您想使用定义为 JS 对象的样式,我建议避免上面代码块中的间接。或者,考虑使用 CSS 模块或直接 CSS。祝你好运!
关于javascript - 样式化组件 - 比 ${props => props.theme...} 更容易访问传递的主题属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47248495/