olo*_*olo 4 reactjs styled-components
this.state.checkBool 是true/false
HTML 结构如下,切换class1和class2
<div class='common class1'>
<div class='common class2'>
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
样式化的组件
const Wrapper = styled.div`
display: block;
background: grey;
// Should this part use props to check true or false?
${prosp => }
`
Run Code Online (Sandbox Code Playgroud)
我被困在如何切换课程上
<Wrapper toggle={this.state.checkBool ? class1 :class2 }/>
Run Code Online (Sandbox Code Playgroud)
您希望将所有 CSS 保留在 中styled.div,并使用toggleprop 来根据其值来决定应为组件使用哪个 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"));Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4694 次 |
| 最近记录: |