简体   繁体   中英

No function call - onclick doesn't work react

I have two components. The first of them looks like this

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      change: false
    };

    this.handleSwitch = this.handleSwitch.bind(this);
  }

  handleSwitch = () => {
    const { change } = this.state;
    this.setState({ change: !change })
    console.log(this.state.change)
  }

  render() {
    const { change } = this.state;

    return (
      <>
        <UserProfilPanel handleSwitch={this.handleSwitch}/>
        {
          change ? <UserProfilGallery /> : <UserProfilContent />
        }
      </>
    );
  }
}

To the UserProfile Panel component, it passes the function which is to be responsible for changing the state.

const UserProfil = (handleSwitch) => {
  return (
    <Container>
      <div>
        <button onClick={() => handleSwitch}>
          gallery
        </button>
        <button onClick={() => handleSwitch}>
          info
        </button>
      </div>
    </Container>
  )
}

When I press some buttons, nothing happens. The console also does not appear an error.

How to fix this problem? I want to change content after clicking the button

First argument in UserProfil() is props . To destructure only a specific property of the props object you need to do:

const UserProfil = ({handleSwitch}) => {...

Then inside your onClick anonymous function you need to call handleSwitch()

<button onClick={() => handleSwitch()}>
                           //      ^^  call function

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM