[英]Pass props to styled-components
我正在使用我的 CMS (prismic.io) 中的 graphql 查询我的反应站点的数据,以便生成以颜色为主题的页面。 我想将变量或道具传递到我的样式组件中,以根据从 CMS 发回的内容更改背景颜色。
在下面的示例中,我的 graphql 查询将返回用户输入的 HEX,然后将其应用于按钮等以设置该页面的主题。
当用户在 CMS 中选择颜色时,颜色可以并且会随着页面的变化而变化。
任何帮助,将不胜感激。 下面的代码示例:
props.data.case_study_color
const ContactButton = styled.button `
background: #004655;
color: #fff;
font-size: 2rem;
padding: 10px;
`;
您可以执行以下操作。
const ContactButton = styled.button`
background: #004655;
color: ${props => props.color || '#fff'};
font-size: 2rem;
padding: 10px;
`;
请参阅此处的代码框示例。
这将是组件代码:
.....component
const [color, setColor] = React.useState("#fff");
React.useEffect(() => {
fetch(URL).then(data => {
setColor(data.response);
});
}, []);
return (
<div className="App">
<ContactButton color={color}>White</ContactButton>
</div>
);
const ContactButton = styled.button `
background: ${props => props.caseStudyColor};
color: #fff;
font-size: 2rem;
padding: 10px;
`;
<ContactButton caseStudyColor={'#004655'} />
由于我的解决方案略有不同,但基于保罗的回答,它可能对其他人有用。
按钮组件
const ContactButton = styled.button`
background: ${props => props.themeColor || '#004655'};`
颜色成分
const themeColor = props.data.case_study_color;
按钮
<ContactButton themeColor={themeColor}>Get in touch</ContactButton>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.