简体   繁体   中英

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. i am just want to set state in grandParent via child click event. i keep getting this error TypeError: this.props.handleButtonChange is not a function would appreciate any help

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.

In grandParent component, you should bind it to current component by keyword bind to pass it through props. this.handleButtonChange = this.handleButtonChange.bind(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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