简体   繁体   English

从另一个组件调用函数(React)

[英]Call function from another component (React)

(React) I have a function in a component (class called SideLogo) (React)我在一个组件中有一个函数(类叫做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() 我正在尝试调用toggleStatus()

As SakoBu already mentioned you can expose a function using the props. 正如SakoBu已经提到的,你可以使用props公开一个函数。 Check out this fiddle: https://jsfiddle.net/wzhdampx/ 看看这个小提琴: https//jsfiddle.net/wzhdampx/

In your other component: 在您的其他组件中:

  _enterHandler() {
    this.toggleStatus();
  }

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

In the SideLog component: 在SideLog组件中:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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