[英]show hide div in react.js
我有这个代码:
class Login extends Component {
constructor(props) {
super(props);
this.state = {
resetPass:true
};
}
resetPassword(resetPass) {
if(resetPass) {
this.setState ({
})
}
}
<div style={{display:`${this.state.resetPass === true ? "none":"block"}`}}>
test 1
</div>
<div style={{display:`${this.state.resetPass === true ? "block" : "none" }`}}>
test2
</div>
所以我创建了一个像这样的按钮
<button onClick = {this.resetPassword(resetPass)} >testing</button>
我想编写一个显示隐藏的div并在react中隐藏当前div的函数? 任何想法如何工作? 提前致谢
constructor(){
super();
this.state = {
resetPass: true
}
}
resetPassword = () => {
this.setState(prevState => ({ resetPass: !prevState.resetPass }));
}
<button onClick = {this.resetPassword} >testing</button>
resetPassword() {
this.setState ({resetPass:this.state.resetPass?false:true})
}
{this.state.resetPass?<div>test1</div>:<div>test2</div>}
<button onClick = {this.resetPassword} > testing</button>
这会为您工作。
resetPassword=()=>{
if(this.state.resetPass) {
this.setState ({
})
}
}
<button onClick = {this.resetPassword} > testing</button>
resetPassword函数不返回任何内容,因此this.resetPassword(resetPass)
等于未定义,因此onClick = {this.resetPassword(resetPass)}
等于onClick = {undefined}。 'bind'函数使您无需调用函数就可以传递参数,并且它返回一个新函数。
onClick = {this.resetPassword.bind(this, resetPass)}
每次调用它时都会返回一个新函数,因此可能会导致一些性能问题。
代替“绑定”,您也可以使用它。
onClick = {() => {this.resetPassword(this, resetPass);}}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.