AnA*_*ice 2 reactjs styled-components
在我的React + StyledComponent应用程序中,我有一个主题文件,如下所示:
theme.js:
const colors = {
blacks: [
'#14161B',
'#2E2E34',
'#3E3E43',
],
};
const theme = {
colors,
};
export default theme;
Run Code Online (Sandbox Code Playgroud)
目前,我可以轻松地使用这些颜色来对组件进行样式设置,如下所示:
const MyStyledContainer = styled.div`
background-color: ${(props) => props.theme.colors.blacks[1]};
`;
Run Code Online (Sandbox Code Playgroud)
问题是,如何将blacks [1]传递给Component作为颜色的道具,如下所示:
<Text color="black[1]">Hello</Text>
Run Code Online (Sandbox Code Playgroud)
其中Text.js是:
const StyledSpan = styled.span`
color: ${(props) => props.theme.colors[props.color]};
`;
const Text = ({
color,
}) => {
return (
<StyledSpan
color={color}
>
{text}
</StyledSpan>
);
};
Text.propTypes = {
color: PropTypes.string,
};
export default Text;
Run Code Online (Sandbox Code Playgroud)
当前,以上内容在DOM中默默地失败和延展了以下内容:
<span class="sc-brqgn" color="blacks[1]">Hello</span>
Run Code Online (Sandbox Code Playgroud)
关于如何使它起作用的任何想法?谢谢
编辑:更新为使用样式组件withThemeHOC
新答案
您可以将组件渲染包装在样式组件提供的<Text>高阶组件(HOC)中withTheme。这使您可以使用<ThemeProvider>直接在React组件中赋予的主题。
示例(基于styled-components docs):
import React from 'react'
import { withTheme } from 'styled-components'
import Text from './Text.js'
class MyComponent extends React.Component {
render() {
<Text color={this.props.theme.colors.blacks[1]} />;
}
}
export default withTheme(MyComponent)
Run Code Online (Sandbox Code Playgroud)
那你可以做
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
Run Code Online (Sandbox Code Playgroud)
旧答案
您可以将主题导入渲染并传递<Text color={theme.blacks[1]} />。
import theme from './theme.js'
...
<Text color={theme.colors.blacks[1]} />
Run Code Online (Sandbox Code Playgroud)
那你可以做
const MyStyledContainer = styled.div`
background-color: ${(props) => props.color};
`;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1913 次 |
| 最近记录: |