如何切换布尔状态以显示/隐藏组件/div



我在ReactJs中有这个任务,我有点被它卡住了:我有一个基类组件,它的状态包含Person和布尔值show。任务是创建一个按钮来切换show状态,当state show为true时,会显示Person配置文件这就是我开始创建状态的方式:

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>
);
}
}

然后我做了一些研究,最后得到了这个代码:

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>
</>
);
}
}

但什么都没发生,屏幕上显示的是我的个人资料,当我点击按钮时,什么也没发生我将感谢的任何帮助

您正在切换"显示";state变量,但没有将其用于任何用途。你需要在此基础上包装你想显示/隐藏应用程序的哪些部分。在React中,通常通过{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>
</>
);
}
}

https://codesandbox.io/s/rough-moon-tl0yx?file=/src/App.js

最新更新