简体   繁体   中英

Call function from another component (React)

(React) I have a function in a component (class called SideLogo)

toggleStatus(flag = !this.state.turned) {
    this.setState({turned: flag})
}

And I have another function in a component

_enterHandler() {
    SideLogo.toggleStatus()
}

I'm trying to call toggleStatus()

As SakoBu already mentioned you can expose a function using the props. Check out this fiddle: https://jsfiddle.net/wzhdampx/

In your other component:

  _enterHandler() {
    this.toggleStatus();
  }

  render() {
    return <SideLogo toggleStatus={func => this.toggleStatus = func} />;
  }

In the SideLog component:

componentDidMount() {
    const { toggleStatus } = this.props;
    if (toggleStatus) {
        toggleStatus(this.toggleStatus);
    }
}

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