简体   繁体   English

将道具传递给孙子 React

[英]Passing Props to grandchild React

Child:孩子:

class Plus extends React.Component{
  constructor(props){
    super(props)
    this.handleClick = this.handleClick.bind(this)
  }

  handleClick(){
    console.log('It's Working!')
    this.props.handleButtonChange()
  }

  render(){
    return (
      <div>
        <i
          className="fa fa-plus fa-2x"
          onClick={() => this.handleClick()}
        ></i>
      </div>
    );
  }
}

export default Plus;

Parent:家长:

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

  render() {
    return (
      <div className="note-creation">
        <form action="">
          <Plus handleButtonChange={this.props.handleButtonChange} />
        </form>
      </div>
    );
  }
}

export default NoteCreation;

GrandParent Component:祖父组件:

class App extends React.Component {
  constructor() {
    super();
    this.state = {
      buttonStat : false
    };
    this.handleButtonChange = this.handleButtonChange(this);

  }

  handleButtonChange(){
    this.setState({
      buttonStat : true
    })
  }


  render() {

    return (
      <div className="App">
        <NoteCreation
          handleButtonChange={this.handleButtonChange}
        />
      </div>
    );
  }
}

export default App;
 

I simply want to pass the method handleButtonChange() from grandParent all the way to child (which is a button), as the button is clicked it triggers the click event which fires up this function making changes in grandparent component(ie setting button state) where am i wrong at or this approach is completely wrong I am really new to react.我只是想将方法handleButtonChange()从grandParent一直传递给子项(这是一个按钮),当按钮被点击时,它会触发点击事件,该事件触发这个功能,在祖父组件中进行更改(即设置按钮状态)我哪里错了或者这种方法完全错误我真的很陌生。 i am just want to set state in grandParent via child click event.我只想通过子单击事件在grandParent 中设置状态。 i keep getting this error TypeError: this.props.handleButtonChange is not a function would appreciate any help我不断收到此错误TypeError: this.props.handleButtonChange is not a function希望得到任何帮助

You have a typo in your top component你的顶层组件有错别字

It should be它应该是

this.handleButtonChange = this.handleButtonChange.bind(this);

and not并不是

this.handleButtonChange = this.handleButtonChange(this);

Alternatively you can declare your method like this或者,您可以像这样声明您的方法

  handleButtonChange = () => {
    this.setState({
      buttonStat : true
    })
  }

without using bind at all.根本不使用bind

In grandParent component, you should bind it to current component by keyword bind to pass it through props.在grandParent组件中,您应该通过关键字bind将其绑定到当前组件以将其传递给props。 this.handleButtonChange = this.handleButtonChange.bind(this); this.handleButtonChange = this.handleButtonChange.bind(this);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM