..."."/> ...".">
Home > Article > Web Front-end > How to implement click to hide and display in react
React method to implement click-to-hide display: 1. Use style to show and hide, code such as "{{display:this.state.isShow?'block':'none'}}"; 2. Use three The meta operator implements hiding and displaying, with code such as "this.state.isShow?(...):(...)"; 3. Display and hide elements through short-circuit logic, with code such as "this.state.isShow&&
...”.
The operating environment of this tutorial: Windows 10 system, react18.0.0 version, Dell G3 computer.
How to hide and display on click in react?
Using the display and hiding methods of elements in react
In react, we have four commonly used methods There is a way to display the display and hiding of elements. Different from vue, in vue we use v-if or v-show to display the hiding and display of elements.
The following will introduce how to hide and display elements in react. Method
<script type="text/babel"> class App extends React.Component { state={ isShow:false, } check=()=>{ this.setState({ isShow:!this.state.isShow }) } render() { return ( <div> {/*第一种方式,用style来显示隐藏*/} <button style={{display:this.state.isShow?'block':'none'}}>张云龙</button> <button style={{display:this.state.isShow?'none':'block'}}>秦霄贤</button> <button onClick={this.check}>点击切换</button> </div> ) } } ReactDOM.render(<App/>,document.getElementById('root'))
block means display, none means hiding
<script type="text/babel"> class App extends React.Component { state={ isShow:false, } check=()=>{ this.setState({ isShow:!this.state.isShow }) } render() { return ( <div> {/*第二种方法,用三元运算符*/} { this.state.isShow?(<div>秦霄贤</div>):(<div>张云龙</div>) } <button onClick={this.check}>点击切换</button> </div> ) } } ReactDOM.render(<App/>,document.getElementById('root'))
<script type="text/babel"> class App extends React.Component { state={ isShow:false, } check=()=>{ this.setState({ isShow:!this.state.isShow }) } render() { return ( <div> {/*第三种方式*/} { this.state.isShow && <div>秦霄贤</div> } { !this.state.isShow && <div>张云龙</div> } <button onClick={this.check}>点击切换</button> </div> ) } } ReactDOM.render(<App/>,document.getElementById('root'))
<script type="text/babel"> class App extends React.Component { state={ isShow:false, love:'秦霄贤' } check=()=>{ this.setState({ isShow:!this.state.isShow }) } loves=(key)=>{ switch(key){ case '秦霄贤': return <div>秦霄贤</div> case '张云龙': return <div>张云龙</div> } } render() { let ok=this.loves(this.state.love) return ( <div> {/*第四种函数形式*/} {ok} <button onClick={this.check}>点击切换</button> </div> ) } } ReactDOM.render(<App/>,document.getElementById('root'))
Recommended learning: "react video tutorial"
The above is the detailed content of How to implement click to hide and display in react. For more information, please follow other related articles on the PHP Chinese website!