this.state.checkBool 是 true
/false
像这样的 HTML 结构,切换 class1
和 class2
<div class='common class1'>
<div class='common class2'>
css看起来像
common {
display: block;
background: grey;
}
.class1 {
position: absolute;
left: 1px;
right: auto;
top: 2px;
background: blue;
}
.class2 {
position: absolute;
left: auto;
top: 2px;
right: 30px;
background: yellow;
}
样式化组件
const Wrapper = styled.div`
display: block;
background: grey;
// Should this part use props to check true or false?
${prosp => }
`
我被困在如何切换类(class)上
<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>
最佳答案
您想将所有 CSS 保留在 styled.div
中并使用 toggle
prop 来决定你应该为组件使用哪个 CSS,这取决于它的值。
示例
const Wrapper = styled.div`
display: block;
background: grey;
${props => {
if (props.toggle) {
return `
position: absolute;
left: 1px;
right: auto;
top: 2px;
background: blue;
`;
} else {
return `
position: absolute;
left: auto;
top: 2px;
right: 30px;
background: yellow;
`;
}
}}
`;
class App extends React.Component {
state = { checkBool: false };
componentDidMount() {
setTimeout(() => {
this.setState({ checkBool: true });
}, 1000);
}
render() {
return <Wrapper toggle={this.state.checkBool}> Foo </Wrapper>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<script src="https://unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root"></div>
关于reactjs - 样式组件切换类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54842948/