使用styled-components扩展React组件样式失效问题求助
问题:styled-components扩展自定义React组件样式未生效
我尝试用styled-components扩展自己写的React组件样式,但样式完全没生效。我觉得操作步骤是对的,但肯定哪里漏了,麻烦帮忙看看!
我的代码如下:
import React from "react"; import styled from "styled-components"; const TextContainer = ({ text }) => { return <p dangerouslySetInnerHTML={{ __html: text }} />; }; const Paragraph = styled(TextContainer)` background: red; `; class Home extends React.Component { render() { const { t } = this.props; return <Paragraph text="This is a test" />; } } export default Home;
预期是让<p>标签背景变成红色,但现在完全没效果,请问怎么解决?提前感谢!
解决方案
这个问题的核心原因是:当你用styled-components包装自定义组件时,你的组件必须接收并传递className属性。styled-components会自动生成对应的样式类名,并通过props.className传递给被包装的组件,但如果你的组件没有把这个类名绑定到实际的DOM元素上,样式自然就不会生效。
只需要修改你的TextContainer组件,让它接收className并把这个类名加到<p>标签上即可:
import React from "react"; import styled from "styled-components"; // 接收className参数,并传递给p标签的className属性 const TextContainer = ({ text, className }) => { return <p className={className} dangerouslySetInnerHTML={{ __html: text }} />; }; const Paragraph = styled(TextContainer)` background: red; `; class Home extends React.Component { render() { const { t } = this.props; return <Paragraph text="This is a test" />; } } export default Home;
这样修改后,styled-components生成的红色背景样式就会被正确应用到<p>标签上,你就能看到预期的效果了。
额外补充:如果你的自定义组件是类组件,逻辑也是一样的,需要把this.props.className添加到根DOM元素的className属性中。
内容的提问来源于stack exchange,提问作者sebazelonka
相关产品推荐
相关产品推荐

