Styled-Components 文本或段落

3

是否可能使用styled-components来为文本或段落添加样式?如果可以,我怎样将文本传递给组件呢?

例如,我有这个Footer组件:

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

export default Footer;

我想要从全局类切换到CSS in JS,因此考虑使用styled-components。现在我尝试了以下代码:

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

但是如果我注释掉段落并使用StyledText组件,什么也不会显示。 如果我尝试传递Styled Component text={'HELLO'},我的应用程序会崩溃。 如何将页脚转换为使用styled-components的方式?


1
你要寻找的是 styled.p,而不是 .text,这是你想要渲染的 HTML 元素。 - Agney
哎呀,我以为 .p 会出错。不过,正确的将文本传递给它的方法是什么?那么 styled.text 又是用来做什么的呢?@Agney - user13101751
3个回答

1
您可以更新您的组件,使其看起来像这样:

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"/>

希望这有所帮助。

0

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

// JSX
<StyledText>Hello</StyledText>

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

0

是的,只要它传递了className,您可以为每个 html元素和每个自定义组件设置样式。

此示例涵盖了基本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>
  );
};

Edit serene-hugle-qgsfy


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接