使用样式化组件扩展样式无效 [英] Extending styles with styled-components not working
问题描述
我正在尝试使用 styled-components
扩展React组件的样式,但无法正常工作。
AFAIK,我做的正确,但是也许我遗漏了一些东西...
这就是我所拥有的:
I'm trying to extend styles for a react component using styled-components
but is not working.
AFAIK, I'm doing it the right way, but perhaps I'm missing something...
Here is what I have:
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
,但现在输出看起来像这样:
Of course, the expected result is to have a red background on p
, but right now the output looks like this:
关于如何解决此问题的任何想法?
Any idea on how to solve this? Probably I'm missing something, but I can't realize what.
感谢前进!
推荐答案
如文档所述:
样式化的方法可以完美地在您自己或任何
上运行,方组件,只要,只要它们将传递的className
prop 附加到DOM元素即可。
The styled method works perfectly on all of your own or any third-party components, as long as they attach the passed className prop to a DOM element.
示例
// This could be react-router-dom's Link for example, or any custom component
const Link = ({ className, children }) => (
<a className={className}>
{children}
</a>
);
const StyledLink = styled(Link)`
color: palevioletred;
font-weight: bold;
`;
render(
<div>
<Link>Unstyled, boring Link</Link>
<br />
<StyledLink>Styled, exciting Link</StyledLink>
</div>
);
参考: https://www.styled-components.com/docs/basics#styling-any-component
这篇关于使用样式化组件扩展样式无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!