【问题标题】:Passing props through nested Styled Components通过嵌套的样式组件传递道具
【发布时间】: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


    【解决方案1】:

    所以解决这个问题的最佳方法是使用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 继承它。它可能会有点冗长,但不一定是混乱的。

    您还可以使用 this post by Kent C. Dodds. 中所述的 css 变量 效果也很好,具体取决于您的用例。

    【讨论】:

      【解决方案2】:

      您的示例代码令人困惑,因为您的内部有 Heading。所以让我们调用你的函数组件MyHeadingstyled.h1Heading

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

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

      【讨论】:

      • 嘿琳达,是的,我熟悉主题(以新手的方式)。我会这样做,但要接受这种情况。我们有上面的浅色/深色标题,但是标题组件内部也可能有一个按钮?...好吧,通常只需将主题向下传递,那很好,但是 - 如果按钮位于具有应用了深色主题,然后按钮应该是浅色的(所以它是黑色背景上的白色按钮)......有点难以用语言准确解释,但希望这是有道理的。我想我可以直接将浅色主题应用于 btn,但我担心这会开始变得混乱......
      【解决方案3】:

      不可能,样式化组件中的 props 应该直接传递给组件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-01
        • 2019-11-11
        • 2020-10-28
        • 2016-08-17
        • 2019-02-14
        • 1970-01-01
        • 2021-12-07
        • 2018-11-20
        相关资源
        最近更新 更多