【问题标题】:Styled components and scoping样式化的组件和范围
【发布时间】:2020-08-27 15:39:03
【问题描述】:

我开始使用样式化组件,并且对范围界定有疑问。 这只是一个虚拟示例,但说明了这一点。

所以我有一个组件。我设置了一个名为 Wrapper 的样式化 div,而不是创建另一个样式化组件来处理组,我认为只需向内部 div 添加一个名为 .group 的类并使用像 scss 中的嵌套来设置样式会更容易内部分区。这可行,但使用 className 作为内部 div 的问题是可能与名为 .group

的全局样式发生冲突

那么有没有办法以某种方式避免这种情况,或者我是否必须创建另一个名为 Group 的样式组件来处理该内部 css ?似乎有很多样板文件必须添加另一个样式化组件才能设置内部组件的样式。

   const Wrapper = styled.div`
      color: blue;

      .group {
        padding: 10px;
        color: green;
      }
    `
  const MyComponent = () => {  
    return (
      <Wrapper>
        <div className='group>
         <h1>heading text</h1>
         <h2>subheading text</h2>
        </div>
        <div>This is my blue text</div>
      </Wrapper>
    );
}

这是我的 globalStylesheet 和组。显然这只有一种风格,但它可以有更多的方式来处理全局分组的元素。

export default createGlobalStyle`

  h1, h2, h3, h4, h5, h6 {
    font-family: '.....';
  }
  .group {
    background-color: red;
  }
`;

我知道我也可以这样做

  > div {
    border: 1px solid red;
  }

但我希望能够更明确地使用类名

【问题讨论】:

    标签: styled-components


    【解决方案1】:

    我认为最好为类似的组创建另一个样式组件

    const Group = styled.div`
      padding: 10px;
      color: green;
    `
    

    因此您可以确保正确覆盖样式。如果 Wrapper 中有更多样式,它的可读性就会降低。您还可以轻松地将 Group 组件替换为子组件或作为父组件(在这种情况下,您应该将 Wrapper 的 .group 样式重写为另一个)。

    将来为了防止样板代码,您可以重写现有的样式组件,例如

    const Timer = styled.div`
      background: #ff5f36;
      border-radius: 50%;
      width: 48px;
      height: 48px;
      display: flex;
      justify-content: center;
      align-items: center;
      font-family: GTWalsheim;
      font-size: 32px;
      color: #ffffff;
    `
    
    const TimeIsUp = styled(Timer)`
      width: 172px;
      border-radius: 8px;
    `
    

    编辑

    您还可以轻松地将 Group 组件替换为子组件或作为父组件

    我会尝试在下面的代码中解释

      const MyComponent = () => {  
        return (
          <Wrapper>
            <div className='someClass>
             <Group>  // so you can replace only your component, without rewriting any style 
               <h1>heading text</h1>
               <h2>subheading text</h2>
             </Group>
            </div>
            <div>This is my blue text</div>
          </Wrapper>
        );
      }
    

    我的意思是您可以轻松地将 Group 组件替换为任何代码位置。当您像在 Wrapper 中一样从父级编写样式时,您应该将此 .group 样式从 Wrapper 替换为另一个作为 .group 父级的元素

    【讨论】:

    • 谢谢萨比特。你能给我一个例子,说明“将组组件替换为子组件或作为父组件”的含义吗?谢谢您的其他解释。
    • @me-me,试图在帖子中解释。但看起来有点奇怪)
    • 啊,我明白你现在在说什么了。
    猜你喜欢
    • 2016-10-02
    • 2019-06-10
    • 2017-12-31
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    • 2020-12-15
    • 2020-10-27
    相关资源
    最近更新 更多