Javascript 已传递但未调整的样式化组件道具 constshape=styled.div` 背景色:${props=>props.bgColor | |红色}; ` 功能形状(道具){ console.log(props.bgColor | | |红色) 返回( ) }
我正在通过spread操作符传递以下道具Javascript 已传递但未调整的样式化组件道具 constshape=styled.div` 背景色:${props=>props.bgColor | |红色}; ` 功能形状(道具){ console.log(props.bgColor | | |红色) 返回( ) },javascript,reactjs,styled-components,Javascript,Reactjs,Styled Components,我正在通过spread操作符传递以下道具 const Shape = styled.div` background-color: ${props => props.bgColor || 'red'}; ` function shape(props) { console.log(props.bgColor || 'red') return ( <Shape> </Shape> ) } let
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”}
console.log显示props.bgColor存在并返回蓝色。然而,元素仍然是红色的。我还通过React开发工具确认了道具的存在。我在哪里搞砸了
编辑:解决方案,使用
将道具传递到形状。道具也必须传递到形状:
let square2x2 = { bgColor: "blue"}
<Shape {...square2x2}></Shape>
函数形状(道具){
返回(
)
}
您需要了解,当您将其传递给
shape
时,您仍然不在样式化div对象内部,实例化组件的样式化div对象是shape
内部shape
,内部shape
的道具不在shape
的范围内,因此,您必须将它们传递给Shape
to 您将道具传递到形状
,但这不会将道具传递到形状
…谢谢!这确实解决了问题,你的解释是有道理的。如果我想一次通过所有道具,我需要写什么<代码>我想是错的。我是否需要将styled.div
中的公式调整为类似背景色:${attributes=>attributes.bgColor | | red'}代码>同时通过
传递道具?还是有更好的方法?我只需要写
哇。再次感谢。顺便说一句,我投票支持你,但我的代表人数不足15人,所以不会更新公众分数。我不知道为什么有人否决了你。
function shape(props) {
return (
<Shape bgColor={props.bgColor} />
)
}