【问题标题】:Styled-components props being passed but not adaptingStyled-components 道具被传递但不适应
【发布时间】:2020-02-01 20:49:30
【问题描述】:
const Shape = styled.div`
background-color: ${props => props.bgColor || 'red'};
`

function shape(props) {
    console.log(props.bgColor || 'red')

    return (
        <Shape>    
        </Shape>
    )    
}

我通过扩展运算符传递以下道具。

let square2x2 = { bgColor: "blue"}

<Shape {...square2x2}></Shape>

console.log 显示 props.bgColor 存在并返回蓝色。但是该元素仍然是红色的。我还通过 React 开发工具确认了 props 的存在。我在哪里搞砸了?

编辑:解决方案,使用 &lt;Shape {...props}/&gt; 将道具传递给 Shape

【问题讨论】:

  • 你将 props 传递给 shape,但这不会将 props 传递给 Shape ...

标签: javascript reactjs styled-components


【解决方案1】:

道具也必须传递给Shape:

function shape(props) {    
    return (
        <Shape bgColor={props.bgColor} />
    )    
}

您需要了解,当您将其传递给shape 时,您仍然不在样式化的 div 对象中,实例化组件的样式化 div 对象是shape 内部的Shapeshape 内部的道具不在Shape 的范围内,所以必须将它们传递给Shape 才能。

【讨论】:

  • 谢谢!这确实解决了它,你的解释是有道理的。如果我想一次通过所有的道具,我需要写什么?我认为&lt;Shape props={props} /&gt; 是错误的。我是否需要将styled.div 中的公式调整为background-color: ${attributes =&gt; attributes.bgColor || 'red'};,同时通过&lt;Shape attributes={...props}/&gt; 传递道具?还是有更好的办法?
  • 我只需要写&lt;Shape {...props}/&gt; 哎呀。再次感谢。顺便说一句,我投票给你,但我的代表少于 15,所以它不会更新公共分数。不知道为什么有人对你投了反对票。
猜你喜欢
  • 1970-01-01
  • 2019-10-07
  • 1970-01-01
  • 2020-05-14
  • 2018-12-01
  • 1970-01-01
  • 2021-12-25
  • 2021-05-01
  • 2022-06-19
相关资源
最近更新 更多