首页 > 解决方案 > 如何知道另一个子组件中一个子组件的事件

问题描述

class Dashboard extends Component {
  render() {
    return (
      <div className="row">
        <SidePanel />
        <DashboardContentPanel />
      </div>
    );
  }
}

我的问题是:在 sidePanel 中,有 6 个按钮,根据点击的按钮,我想更改 DashboardContentPanel 的内容

我是 ReactJS 的新手!帮我。只是一个逻辑!

标签: reactjs

解决方案


您可以使用ref来访问整个组件功能

假设您的DashboardContentPanel组件有一个调用的函数myFunctionButtonOne,并且您需要在组件中单击按钮时触发此函数SidePanel,因此该Dashboard组件将成为 ( SidePanel, DashboardContentPanel) 组件之间的中介

class Dashboard extends Component {
  render() {
    return (
      <div className="row">
        <SidePanel handleButtonOne={this.panel.myFunctionButtonOne} />
        <DashboardContentPanel ref={(panel)=> this.panel = panel} />
      </div>
    );
  }
}

当我们将 handleButtonOne 作为道具传递时,我们可以像这样使用它

<button onClick={this.props.handleButtonOne}>Click me</button>

推荐阅读