【问题标题】:Styled-Components Text or Paragraphs样式化组件文本或段落
【发布时间】:2020-07-16 22:36:06
【问题描述】:

是否可以使用样式组件设置文本或段落的样式?如果是,如何将文本传递到组件中?

例如,我有这个 Footer 组件:

const Footer = () => (
  <footer className="site-footer">
    <p className="text"> HELLO</p>
    <Copyright
      link={'https://hotmail.com'}
      text={'HELOO'}></Copyright>
  </footer>
);

export default Footer;

我想从全局类切换到 js 中的 css,这就是我想到使用 styled-components 的原因。现在我尝试了这个:

export const StyledText = styled.text`
    text: Hellooo
    color: white;
    text-align: center;
`

但是,如果我注释掉该段落并使用 StyledText 组件,则什么都不会显示。如果我尝试通过 Styled Component text={'HELLO'} 我的应用程序崩溃。如何以使用样式组件的方式转换页脚?

【问题讨论】:

  • 您正在寻找 styled.p 而不是 .text,这是您要呈现的 HTML 元素
  • 糟糕,我以为.p出错了。然而,将文本传递给它的正确方法是什么?那么styled.textfor 是什么? @Agney

标签: javascript css reactjs typescript styled-components


【解决方案1】:

styled-components 只处理组件的样式而不是内容。所有children 都将被保留,因此您可以执行以下操作:

// JSX
<StyledText>Hello</StyledText>

// StyledText.js
export default styled.p`
  color: white;
  text-align: center;
`;

【讨论】:

    【解决方案2】:

    您可以将组件更新为如下所示:

    import styled from 'styled-components';
    
    const StyledText = styled.p`
      color: white;
      text-align: center;
    `;
    
    export default function Footer({text}){
      return   <footer className="site-footer">
        <StyledText>{text}</StyledText>
        <Copyright
          link={'https://hotmail.com'}
          text={text}/>
      </footer>;
    }
    

    您将能够像这样调用Footer 组件:

    <Footer text="HELLO"/>
    

    希望这会有所帮助,

    【讨论】:

      【解决方案3】:

      是的,您可以设置每个html 元素和每个自定义组件的样式,只要它通过className

      这个例子几乎涵盖了基本的 API:

      const Text = styled.p`
        color: blue;
        text-align: center;
      `;
      
      const Copyright = ({ className, link, text }) => (
        <div className={className}>
          <Text>{link}</Text>
          <Text>{text}</Text>
        </div>
      );
      
      const StyledCopyright = styled(Copyright)`
        border: 1px black solid;
        ${Text} {
          color: palevioletred;
        }
      `;
      
      const Footer = () => {
        return (
          <footer>
            <Text>HELLO</Text>
            <Copyright link="https://hotmail.com" text="World" />
            <StyledCopyright link="https://hotmail.com" text="World" />
          </footer>
        );
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-05-24
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 2013-01-29
        • 2016-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多