从下到上通过嵌套的组件传递事件

时间:2019-01-30 21:35:46

标签: reactjs

虽然这个问题已经被问过我没有找到答案。我的组件嵌套在曾孙的层次上,我不知道如何从底部到顶部获取数据。

<Parent/>
  <Child/>
    <GrandChild/>
      <GreatGrandChild/>

查看示例:fiddle

曾孙是表格,我希望输入数据到达顶部的父级。当它仅嵌套一层深度时,我可以使用它,但是现在它被深度嵌套了,所以它不起作用。我不确定如何将事件传递到两个级别。

我听说可以使用redux,但是我想知道是否有避免的方法。或者,如何避免嵌套?即使是通过他们都是真正独立的组件应该我只是将它们移动到一个大的组成部分?这可能有效,但似乎是不好的做法?

4 个答案:

答案 0 :(得分:1)

Redux对于简单传递道具来说是多余的。您可以通过每个孩子传递道具,但是像这样使用Context API会更容易:

父项:

const MyContext = React.createContext('default');
export MyContext;

class Parent extends React.Component {
    myFunction() {
        //Do something here
    }

    render() {
         return (
            <MyContext.Provider value={this.myFunction}>
                <ChildComponent />
            </MyContext.Provider>
         );
    }
}

export default Parent;

子组件:

import { MyContext } from './Parent';

class ChildComponent extends React.Component {
    render() {
        const { myFunction } = this.context;
        return (
            <div onClick={myFunction}>Click Me!</div>
        );
    }
}

ChildComponent.contextType = MyContext;

只要导入,您就可以使用任意深度的上下文。

答案 1 :(得分:1)

非常简化,您可以将功能传递给所有组件:

class GreatGrandChild extends React.Component {
  render() {
    return (
      <div>
      <input onChange={this.props.onChange}/>
        <h2>I'm the GreatGrandChild</h2>
      </div>
    )
  }
}

class GrandChild extends React.Component {
  render() {
    return (
      <div>
        <h2>I'm the GrandChild</h2>
        <GreatGrandChild onChange={this.props.onChange}/>
      </div>
    )
  }
}

class Child extends React.Component {
  render() {
    return (
      <div>
      <GrandChild onChange={this.props.onChange}/>
        <h2>I'm the child</h2>
      </div>
    )
  }
}
class Top extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
    }
  }

  handleChildchange = (e) => {
    console.log('child event on parent')
    console.log(e.target.value);
  }
  render() {
    return (
      <div>
       <Child onChange={this.handleChildchange}/>
        <h2>I'm the parent</h2>
      </div>
    )
  }
}

ReactDOM.render(<Top />, document.querySelector("#app"))

答案 2 :(得分:0)

只需通过道具从父级传递回叫,并确保将其一直传递到您需要的地方。

答案 3 :(得分:0)

您还可以在嵌套中将prop传递给每个子组件,并且每当值更改时,都可以调用父函数(嵌套)以获取父函数中的最新值。