簡體   English   中英

從另一個組件調用函數(React)

[英]Call function from another component (React)

(React)我在一個組件中有一個函數(類叫做SideLogo)

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

我在組件中有另一個功能

_enterHandler() {
    SideLogo.toggleStatus()
}

我正在嘗試調用toggleStatus()

正如SakoBu已經提到的,你可以使用props公開一個函數。 看看這個小提琴: https//jsfiddle.net/wzhdampx/

在您的其他組件中:

  _enterHandler() {
    this.toggleStatus();
  }

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

在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