【问题标题】:styled components in functional component does not apply style to component功能组件中的样式化组件不会将样式应用于组件
【发布时间】:2021-01-15 14:51:44
【问题描述】:
import React from 'react';
import styled from 'styled-components';
import { Typography } from 'antd';
const { Title } = Typography;
const StyledTitle = styled(Title)`
    align-self: center;
    color: rgb(140, 140, 140);
`;
export function Header(props : {children : React.ReactNode}) {
    return <StyledTitle>{props.children}</StyledTitle>;
}
export default Header;

我想将文本颜色更改为rgb(140, 140, 140)。但是颜色没有改变。

我在下面的其他组件中使用Header 组件。

import { Header } from './Header';
export function Login() {
    return(
        <Container>
            <Header>Login</Header>
        </Container>
    );
}

如果我设置background-color: yellow;,它适用。

因此,我很困惑。某些样式有效,而其他样式无效...

【问题讨论】:

  • 好吧,如果您检查样式,您会看到它的来源。可能的 antd 样式比你的更具体。
  • @YuryTarabanko 我很难理解antd 样式如何比组件更具体。你能帮我解释一下吗?以及如何将我的样式设置为比 antd 更具体?
  • “antd 样式如何比组件更具体”,嗯,有很多方法。例如,这些选择器可能有标签名称h1.ant-typography 比来自 SC 的 '.my-class' 更具体。只需打开开发工具并检查哪种样式有效地适用。

标签: javascript css reactjs styled-components


【解决方案1】:

试试这个:

color: rgb(140, 140, 140)!important;

【讨论】:

  • 不,这是你能想到的最糟糕的方法。
  • 感谢您的建议。你能解释一下为什么在这种情况下我不应该这样做吗?
  • 重要的是一个基本上固定财产的逃生舱口。它的优先级高于内联样式。基本上,您的代码变得难以维护。在 OP 案例中没什么大不了的,但如果用作一般方法,可能会破坏整体开发人员体验。
猜你喜欢
  • 2019-03-03
  • 2019-02-14
  • 2021-12-14
  • 2020-10-27
  • 2021-04-13
  • 2021-01-12
  • 2021-03-24
  • 2021-04-13
  • 2019-10-18
相关资源
最近更新 更多