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 => }
`
我被困在如何切换班级
<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>
答案 0 :(得分:1)
您希望将所有CSS都保留在styled.div
中,并使用toggle
属性根据其值来决定对组件使用哪种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>