【发布时间】:2017-08-11 03:47:22
【问题描述】:
我正在使用 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 属性值的正确样式:
function StyledDemo({ name, ...props })
Parent 元素在以下情况下不使用基于 light 属性值的正确样式:
function StyledDemo({ name, light, ...props })
我可以通过在 Parent 和 Child 组件上设置 prop 来完成所有工作,但这似乎不是最好的方法:
return (
<Parent {...props} light={light}>
<Child light={light}>{name}</Child>
</Parent>
);
这是基于 props 将样式应用于组件的正确方法,还是我的方法有问题?
如果有帮助,我有一个演示可以修改: https://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz
【问题讨论】: