我正在使用 styled-components 为组件中的父元素和子元素设置样式:
function StyledDemo({
name,
light,
...props
}) {
return (
<Parent {...props}>
<Child>{name}</Child>
</Parent>
);
}
我有一个light
真/假的道具 - 但我在根据该属性的值设置元素样式时遇到问题:
const Parent = styled.div`
background-color: #000;
width: 100%;
${props => props.light && `
background-color: #ccc;
`}
`;
仅当我删除单独传递给函数的道具时,样式似乎才起作用。
Parent
在以下情况下,元素会根据light
prop 值使用正确的样式:
function StyledDemo({ name, ...props })
Parent
在以下情况下,元素不会根据light
prop 值使用正确的样式:
function StyledDemo({ name, light, ...props })
我可以通过在Parent
andChild
组件上设置 prop 来完成所有工作,但这似乎不是最好的方法:
return (
<Parent {...props} light={light}>
<Child light={light}>{name}</Child>
</Parent>
);
这是基于道具将样式应用于组件的正确方法,还是我的方法有问题?
如果有帮助,我有一个演示可以修改: https ://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz