【发布时间】:2021-01-23 21:13:25
【问题描述】:
我正在使用样式化组件,我想知道是否有必要使用 ThemeProvider。
这是文档中的示例。
// Define our button, but with the use of props.theme this time
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
/* Color the border and text with theme.main */
color: ${props => props.theme.main};
border: 2px solid ${props => props.theme.main};
`;
// We are passing a default theme for Buttons that arent wrapped in the ThemeProvider
Button.defaultProps = {
theme: {
main: "palevioletred"
}
}
// Define what props.theme will look like
const theme = {
main: "mediumseagreen"
};
render(
<div>
<Button>Normal</Button>
<ThemeProvider theme={theme}>
<Button>Themed</Button>
</ThemeProvider>
</div>
);
但我想知道我是否可以这样做:
// theme.js
const theme = {
main: "mediumseagreen"
};
export default theme;
// main.js
import theme from 'theme';
const Button = styled.button`
font-size: 1em;
margin: 1em;
padding: 0.25em 1em;
border-radius: 3px;
/* Color the border and text with theme.main */
color: ${theme.main};
border: 2px solid ${theme.main};
`;
render(
<div>
<Button>Themed</Button>
</div>
);
如果我不需要Normal Button(所有按钮都将是主题),并且我不需要动态主题(例如更改为暗模式),我可以使用第二种方法吗?有什么我没有想到的缺点吗?
【问题讨论】: