javascript - How to toggle a boolean state to show/hide a component/div?
问题描述
I have this task in ReactJs and I'm kinda stuck with it : I have a based class component with a state containing Person and a boolean show the task is to create a button that toggle the show state and when the state show is true the person profile appear this is the how i started creating the state :
class App extends React.Component {
state = {
Person: {
fullName : "Naruto Uzumaki",
bio : "I just love ramen",
imgSrc : {myImage},
profession : "7th Hokage"
},
show : false
};
render() {
return (
<div className="App">
Hello!
</div>
);
}
}
then I did some research and I end up with this code:
class App extends React.Component {
state = {
Person: {
fullName : "Naruto Uzumaki",
bio : "I just love ramen",
imgSrc : myImage,
profession : "7th Hokage"
},
show : false,
};
handleShowPerson = () => {
this.setState({
...this.state.Person,
show: !this.state.show,
});
}
render() {
return (
<>
<h1>{this.state.Person.fullName}</h1>
<h1>{this.state.Person.bio}</h1>
<img src={this.state.Person.imgSrc} alt="Naruto"></img>
<h1>{this.state.Person.profession}</h1>
<br></br>
<button onClick={this.handleShowPerson}>click here</button>
</>
);
}
}
But nothing is happening the screen is showing me profile adn when I click on the button nothing happen I will appreciate any help
解决方案
You're toggling the "show" state variable, but aren't using it for anything. You need to wrap what parts of the app you want to show/hide based on that. In React, you generally do that by {someBooleanVariable && (<SomeJSX />)}
class App extends React.Component {
state = {
Person: {
fullName: "Naruto Uzumaki",
bio: "I just love ramen",
imgSrc: myImage,
profession: "7th Hokage"
},
show: true
};
handleShowPerson = () => {
this.setState({
...this.state,
show: !this.state.show
});
};
render() {
return (
<>
{this.state.show && (
<>
<h1>{this.state.Person.fullName}</h1>
<h1>{this.state.Person.bio}</h1>
<img src={this.state.Person.imgSrc} alt="Naruto"></img>
<h1>{this.state.Person.profession}</h1>
<br></br>
</>
)}
<button onClick={this.handleShowPerson}>click here</button>
</>
);
}
}
推荐阅读
- reactjs - 使用 axios 和 react 从服务器获取数据
- python-3.x - lightgbm.cv 方法的输出
- java - 如何拆分包/合并模块
- sql - 尝试在 SQL Server 2014 中创建视图以读取不同格式的表数据
- excel - #场地!在单元格中,但单击单元格时,正确的值在公式框中
- python - 如何设置使用 pipenv 运行 pytest 的 GitHub 操作?
- c# - 无法将类型 [具体] 隐式转换为 [接口]
- excel - 如果 C 列中的单元格 = 0,则使用宏将单元格从一个工作表复制到另一个工作表
- javascript - 如何避免 FireFox 由于行高舍入而切断垂直居中的文本(Chrome 没有问题)
- asp.net - 为什么 Page.User.Identity.Name 有时显示域部分,有时不显示