将道具传递给样式组件 [英] Pass props to styled-components
问题描述
我正在使用来自我的 CMS (prismic.io) 的 graphql 为我的 react 站点查询数据,以生成颜色主题页面.我想将一个变量或道具传递到我的样式组件中,以根据从 CMS 发回的内容更改背景颜色.
在下面的示例中,我的 graphql 查询将返回用户输入的 HEX,然后将其应用于按钮等以主题该页面.
当用户在 CMS 中选择颜色时,颜色会随着页面的变化而变化.
任何帮助将不胜感激.下面的代码示例:
道具
props.data.case_study_color
组件
const ContactButton = styled.button `背景:#004655;颜色:#fff;字体大小:2rem;填充:10px;`;
您可以执行以下操作.
const ContactButton = styled.button`背景:#004655;颜色:${props =>props.color ||'#fff'};字体大小:2rem;填充:10px;`;
请参阅此处的代码沙盒示例.
这里是组件代码:
.....组件const [color, setColor] = React.useState("#fff");React.useEffect(() => {获取(网址).然后(数据=> {设置颜色(数据.响应);});}, []);返回 (<div className="应用程序"><ContactButton color={color}>White</ContactButton>
);
I am querying data for my react site using graphql from my CMS (prismic.io) in order to produce color themed pages. I want to pass a variable or props into my styled component to change the background color based on what is sent back from the CMS.
In the below example, my graphql query will return a HEX that has been inputted by the user, this would then be applied to buttons etc to theme that page.
The colour can and will change from page to page as the user will be selecting it within the CMS.
Any help would be appreciated. Code example below:
Props
props.data.case_study_color
Component
const ContactButton = styled.button `
background: #004655;
color: #fff;
font-size: 2rem;
padding: 10px;
`;
You could do the following.
const ContactButton = styled.button`
background: #004655;
color: ${props => props.color || '#fff'};
font-size: 2rem;
padding: 10px;
`;
Here would be the component code:
.....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>
);
这篇关于将道具传递给样式组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!