首页 > 解决方案 > 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

标签: javascriptreactjs

解决方案


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

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


推荐阅读