【问题标题】:Styled Components - why does prop position affect styling?样式组件 - 为什么道具位置会影响样式?
【发布时间】: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 })

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

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

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

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

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    这与styled-components无关,而是与rest参数有关。

    当您执行其余运算符时,您按名称“挑选”出的任何属性都不会包含在 ...rest 变量中。所以当你这样做时

    const Button = ({ light, ...rest }) => ()
    
    <Button light primary />
    

    rest 将只包含primary 属性,但不包含light,这是它自己的变量。

    如果你这样做了

    const Button = ({ ...rest }) => ()
    
    <Button light primary />
    

    rest 也将包含light

    所以在你的例子中,你从...props中挑选出light,所以当你将{...props}传递给父级时,它不再包含light,所以styled-components不知道它存在!要么使用第一个版本,要么必须手动将其应用到每个组件。

    查看MDN了解更多关于rest参数的信息!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-23
      • 2018-09-21
      • 2020-01-21
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2019-03-03
      • 2016-01-24
      相关资源
      最近更新 更多