首页 > 解决方案 > ReactJS - 从子组件调用父方法并等待父响应

问题描述

我刚开始使用 ReactJS,所以我还在掌握它的窍门。我需要一些我没有找到答案的方面的帮助。我正在尝试从子组件调用父组件中的函数,但我也想从父组件接收包含一些数据的答案。我怎样才能做到这一点?目前我正在做的是:

import Parent from './parent.js';
class Child extends React.Component {
    constructor(props) {
        super(props);
        };

    click = () => {
        this.props.parentMethod();
    }

    render() {
          <div onClick={this.click}>Hello Child</div>
    }
}

class Parent extends React.Component {
    constructor(props) {
        super(props);
        };

    someMethod() {
        console.log('bar');
    }

    render() {
          <Child parentMethod={this.someMethod}>Hello Parent, {this.props.children}</Child>
    }
}

标签: reactjs

解决方案


你通常不会这样做。数据从 React 中的 parent » child 流出。Parent因此,如果对传递给 的更改数据执行函数Child,您的Child组件将重新渲染。

使用您的示例:

class Child extends React.Component {
  render() {
    <div onClick={this.props.changeName}>
      Hello, {this.props.displayName}
    </div>
  }
}

class Parent extends React.Component {
  constructor(){
    this.state = {
      name: "Bob",
    }
  }

  changeName = () => {
    this.setState({ name: "Sally" })
  }

  render() {
    return(
      <Child
        changeName={this.changeName}
        displayName={this.state.name}
      />
    )
  }
}

在这种情况下,单击div内部Child将更改's的name属性,然后将其传递给并重新渲染。ParentstateChild


推荐阅读