![](/img/trans.png)
[英]Not working Server side rendering Styled-Components with Next JS
[英]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
};
建议:
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.