使用 this.props.children 时将父函数传递给 child


class Parent extends React.Component {
  foo() {
    console.log('i was called');
  }
  render() {
    return(
      this.props.childen;
    );
  }
}
class Child extends React.Component {
  render() {
    return(
      <div onClick="call foo here">Child</div>
    );
  }
}
React.render(<Parent><Child></Parent>, document.getElementById('View'));

我试图像最后一行所示的那样渲染孩子。在这种情况下,如何将foo()从父传递到子级?

我知道通常在父母的渲染中我们会做<Child func={this.foo} />

您可以在 Parent 的渲染方法中调用 Child,并将函数 foo 作为道具传递给它。然后在子组件上,您可以将其作为 props 检索。

 class Parent extends React.Component {
      foo() {
        console.log('i was called');
      }
      render() {
        return(
          <Child foo={this.foo} />
        );
      }
    }
    class Child extends React.Component {
    render() {
        return(
          <div onClick={this.props.foo}>Child</div>
        );
      }
    }
    React.render(<Parent />, document.getElementById('View'));

最新更新