首页 > 解决方案 > Styled-components 道具被传递但不适应

问题描述

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 的存在。我在哪里搞砸了?

编辑:解决方案,将道具传递给 Shape<Shape {...props}/>

标签: javascriptreactjsstyled-components

解决方案


道具也必须传递给 Shape:

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

您需要了解,当您将其传递给shape您时,您仍然不在样式化的 div 对象中,实例化组件的样式化 div 对象在Shape里面shape,里面的道具在shape范围之外Shape,所以您必须将它们传递给Shapeto。


推荐阅读