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

我有这个带有一些属性的React组件,并且我希望样式仅在该属性具有值的情况下才能应用,我尝试了如下操作:

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

I'm not passing the property size, so I want the font-size to be the default value I specified (font-size: ${props => props.size !== undefined ? props.size : '1.3em'})

但是,这不起作用。我在这里想念什么?提前致谢。

评论
  • 你无可取代
    你无可取代 回复

    you have incorrectly defined the value for textProps. By using [], you have made each property into an array which is why it doesn't work when you try to use it in styled-component

    如下使用

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