[英]styled-components not applying style to custom functional react component
當使用styled-components
為自定義功能性反應組件設置樣式時,不會應用這些樣式。 這是一個簡單的示例,其中樣式未應用於StyledDiv
:
const Div = () => (<div>test</div>)
const StyledDiv = styled(Div)`
color: red;
`;
確保正確應用樣式的最佳方法是什么?
從文檔 :
樣式化的方法可以完美地在您自己的所有第三方組件上運行,也可以在任何第三方組件上完美運行,只要它們將className prop傳遞給其呈現的子組件,子組件也應該通過它,依此類推。 最終,必須將className向下傳遞到實際的DOM節點,以使樣式生效。
例如,您的組件將變為:
const Div = ({ className }) => (<div className={className}>test</div>)
const StyledDiv = styled(Div)`
color: green;
`;
修改示例:
const styled = styled.default const Div = ({ className }) => (<div className={className}>test</div>) const StyledDiv = styled(Div)` color: green; font-size: larger; `; const App = () => { return(<StyledDiv>Test</StyledDiv>) } ReactDOM.render(<App />, document.querySelector('.app'))
<script src="//unpkg.com/react@16.5.2/umd/react.development.js"></script> <script src="//unpkg.com/react-dom@16.5.2/umd/react-dom.development.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/styled-components/3.4.9/styled-components.min.js"></script> <div class="app"></div>
像這樣使用styled(Component)
創建一個類,該類作為名為className
的prop傳遞給包裝的組件。
然后可以將其應用於根元素:
const Div = ({ className }) => (
<div className={className}>test</div>
)
const StyledDiv = styled(Div)`
color: red;
`;
如果您不能更改原始組件(導入或生成),則假定該組件為<span>
,可以將其包裝為例如<div>
並嵌套css規則,如下所示:
const ComponentICantTouchWrapper = ({className}) => (
<div className={className}><ComponentICantTouch /></div>
);
const StyledComponentICantTouch = styled(ComponentICantTouchWrapper)`
> span {
color: red;
}
`;
就我而言,我試圖使用帶有材質 UI 的樣式組件。 我的想法是這樣做:(在大多數情況下都有效)
const StyledTableRow = ({ className, children }) => (
<TableRow className={className}>{children}</TableRow>
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.