【问题标题】:styled-components: style based on non-styled class parentstyled-components:基于非样式类父的样式
【发布时间】:2021-01-28 08:09:42
【问题描述】:

假设我有这个:

const Child = styled.button`
    background-color: grey;
`;

<div className="some-non-styled-class">
    <Child>Hello World</Child>
</div>;

<div className="some-other-non-styled-class">
    <Child>Hello World</Child>
</div>;

如何设置 Child 的样式,使其在 some-non-styled-class 下为“红色”,在 some-other-non-styled-class 下为“蓝色”?

我知道ability to refer to other styled-components,但我有一个用例,我需要根据具有静态类名的现有库更改样式。

【问题讨论】:

    标签: reactjs styled-components


    【解决方案1】:

    你可以试试这样的:

    export const Child = () => {
    const [parentClass, setParentClass] = useState("")
    
    useEffect(() => {
      const currentClass = document.querySelector(".childComp").parentElement.className
      setParentClass(currentClass)
    },[])
    
    return (<MyStyledComponent className="childComp" parentClassName={parentClass}>
      {children}
      </MyStyledComponent>)
    }
    

    【讨论】:

    • 不,因为我没有关于父母的任何详细信息。父级来自另一个库/团队,它独立于我的组件更改类名。这是一个糟糕的情况,但这是我必须解决的问题。
    猜你喜欢
    • 2018-01-18
    • 1970-01-01
    • 2021-08-26
    • 2020-01-16
    • 2018-09-06
    • 2018-10-20
    • 2021-11-01
    • 1970-01-01
    • 2019-12-21
    相关资源
    最近更新 更多