1

我正在使用 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在以下情况下,元素会根据lightprop 值使用正确的样式:

function StyledDemo({ name, ...props })

Parent在以下情况下,元素不会根据lightprop 值使用正确的样式:

function StyledDemo({ name, light, ...props })

我可以通过在ParentandChild组件上设置 prop 来完成所有工作,但这似乎不是最好的方法:

return (
  <Parent {...props} light={light}>
    <Child light={light}>{name}</Child>
  </Parent>
);

这是基于道具将样式应用于组件的正确方法,还是我的方法有问题?

如果有帮助,我有一个演示可以修改: https ://www.webpackbin.com/bins/-Kfcsujw99cjU7ttqgTz

4

1 回答 1

1

这与其余参数无关,styled-components但与其余参数有关。

当您执行其余运算符时,您按名称“挑选”出的任何属性都不会包含在...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 !

于 2017-03-20T09:03:32.363 回答