gpt4 book ai didi

javascript - 样式组件未将样式应用于自定义功能 react 组件

转载 作者:行者123 更新时间:2023-12-01 14:46:14 25 4
gpt4 key购买 nike

使用 styled-components 时为自定义功能性 react 组件设置样式,未应用样式。这是 simple example样式未应用于 StyledDiv :

const Div = () => (<div>test</div>)
const StyledDiv = styled(Div)`
color: red;
`;

确保正确应用样式的最佳方法是什么?

最佳答案

来自 docs :

The styled method works perfectly on all of your own or anythird-party components as well, as long as they pass the classNameprop to their rendered sub-components, which should pass it too, andso on. Ultimately, the className must be passed down the line to anactual DOM node for the styling to take any effect.


例如,您的组件将变为:
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>

关于javascript - 样式组件未将样式应用于自定义功能 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52542817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com