繁体   English   中英

通过嵌套的样式组件传递道具

[英]Passing props through nested Styled Components

采取这个简单的情况:

我有一个容器,里面嵌套了一个 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}而不声明它两次吗?
还是我误解了样式化组件的行为方式?

您的示例代码令人困惑,因为您自己有Heading 因此,让我们调用您的 function 组件MyHeadingstyled.h1 Heading

道具不会从父母级联到孩子。 这与样式化组件无关,这只是 React 的工作方式。 如果您想将道具传递给孩子,那么您必须像在第二个片段中所做的那样自己做。

也就是说,在这种特殊情况下,我不认为传递道具是通往 go 的方式。 浅色或深色主题本质上是全局性的,因此我们希望通过React 上下文使主题可用,而不是将其从组件传递到组件。 styled-components 对此有一些内置支持 您可以将应用程序的全部内容放在ThemeProvider中。 它使得它下面的层次结构中的所有样式组件都可以访问theme道具。

所以解决这个问题的最好方法是使用themes 由于您的容器是样式组件,因此它具有内置功能。

所以如果你给它添加一个主题道具,它会将主题级联到每个子元素,这也是一个样式组件:

export function Heading(props) {
return (
    <Container theme={{mode: 'light'}}>
      <Heading> // this heading would receive this theme object as a prop.
        {props.text}
      </Heading>
    </Container>
  )
}

export const Heading = styled.h1`
  background-color: ${({theme}) => theme.mode === "dark" ? "white" : "black"};
`;

export const ButtonInsideHeading = styled.h1`
  background-color: ${({theme}) => theme.mode === "light" ? "black" : "white"};
`;

您在评论中提到的那个按钮也是如此。 Styled-components 将注入这个主题道具,无论它们有多少层次。 因此,您的 Button 样式组件将从Heading继承theme ,该主题从Container继承。 它可能会有点冗长,但不一定是混乱的。

您还可以使用Kent C 在这篇文章中描述的 css 变量。 多兹。 效果也很好,具体取决于您的用例。

这是不可能的,样式组件中的道具应该直接传递给组件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM