【发布时间】:2021-04-29 10:34:59
【问题描述】:
以这个简单的情况为例:
我有一个容器,其中嵌套了一个 h1。 我想将一些道具传递给这两个元素,这些道具将根据明暗主题改变它们的颜色;例如:白色文字/黑色背景||黑色文字/白色背景
问题:看起来传递给样式化组件的道具(颜色和文本)并没有像我假设的那样层叠。
简单示例:
export function Heading(props) {
return (
<Container {...props}> // I would expect the props obj to be available by nested Heading el
<Heading>
{props.text}
</Heading>
</Container>
)
}
// styled components
export const Container = styled.div`
padding: 20px;
background-color: ${props => props.color === dark ? "black" : "white";
`;
export const Heading = styled.h1`
background-color: ${props => props.color === dark ? "white" : "black"; // does not take affect
`;
相反,我必须这样做:
<Container {...props}> // Pass to container
<Heading {...props}> // Pass to heading el
{props.text}
</Heading>
</Container>
问题:
我可以让Heading 获取传递给Container 的{...props} 而不声明两次吗?
还是我误解了样式化组件的行为方式?
【问题讨论】:
标签: javascript css reactjs styled-components