我使用样式组件来设置组件中父元素和子元素的样式:
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
道具值的正确样式:
function StyledDemo({ name, light, ...props })
我可以通过在Parent
和Child
组件上设置道具来完成所有工作,但这似乎并不是最好的方法:
return (
<Parent {...props} light={light}>
<Child light={light}>{name}</Child>
</Parent>
);
这是基于道具将样式应用于组件的正确方法,还是我的方法存在问题?
如果有帮助的话,我有一个演示来修补: https://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz
答案 0 :(得分:1)
这与styled-components
无关,而与rest参数无关。
当您执行rest操作符时,您按名称“选择”的任何属性都不会包含在...rest
变量中。所以当你这样做时
const Button = ({ light, ...rest }) => ()
<Button light primary />
rest
只包含primary
属性,但不包含light
,现在它是自己的变量。
如果你做了
const Button = ({ ...rest }) => ()
<Button light primary />
而rest
也包含light
。
因此,在您的示例中,您从light
中选择...props
,因此当您将{...props}
传递给父级时,它不再包含light
,所以styled-components
不知道它存在!您可以使用第一个版本,也可以手动将其应用于每个组件。
有关rest参数的详细信息,请参阅MDN!