繁体   English   中英

条件渲染不适用于样式化组件

[英]Conditional rendering not working with styled-components

我有这个带有一些属性的 React 组件,并且我希望 styles 仅在属性具有值时才应用,我尝试了这样的事情:

export const Text = ({text, color, size, fontFamily}) => {

    const StyledParagraph = styled.p`
        margin: 0;
        font-size: ${props => props.size !== undefined ? props.size : '1.3em'};
    `;

    const textProps = {
        text: [text],
        color: [color],
        size: [size],
        fontFamily: [fontFamily],
    }

    return (
        <StyledParagraph {...textProps}>{text}</StyledParagraph>
    )
}

我这样称呼它:

<Text text="some text"/>

我没有传递属性size ,所以我希望font-size是我指定的默认值( font-size: ${props => props.size?== undefined. props:size. '1.3em'} )

但是,这是行不通的。 我在这里想念什么? 提前致谢。

您错误地定义了 textProps 的值。 通过使用[] ,您将每个属性都制作成一个数组,这就是为什么当您尝试在 styled-component 中使用它时它不起作用的原因

像下面这样使用它

const textProps = {
    text: text,
    color: color,
    size: size,
    fontFamily: fontFamily,
}

问题是如何通过将解构的道具放入数组来定义textProps的值。

将其更新为

const textProps = {
  text: text,
  color: color,
  size: size,
  fontFamily: fontFamily
};

编辑递归-诺贝尔-wghcl

建议:

  • StyledParagraph出来,因此不会重新定义Text的每个渲染
  • 解构text并将props的rest传播到props中,传播到渲染的StyledParagraph
  • 将字体大小逻辑简化为简单的后备值。

代码

const StyledParagraph = styled.p`
  margin: 0;
  font-size: ${props => props.size || "1.3rem"};
`;

const Text = ({ text, ...props }) => {
  return <StyledParagraph {...props}>{text}</StyledParagraph>;
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM