将道具传递给孙子 React

时间:2021-07-06 12:38:01

标签: javascript reactjs react-props react-class-based-component

孩子:

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;

家长:

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;

祖父组件:

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;
 

我只是想将方法handleButtonChange()从grandParent一直传递给child(这是一个按钮),当按钮被点击时,它会触发click事件,该事件触发这个函数,在祖父组件中进行更改(即设置按钮状态) 我哪里错了或者这种方法完全错误我真的很陌生。 我只想通过子单击事件在grandParent 中设置状态。 我不断收到此错误 TypeError: this.props.handleButtonChange is not a function 将不胜感激任何帮助

2 个答案:

答案 0 :(得分:1)

你的顶层组件有错别字

应该是

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

而不是

this.handleButtonChange = this.handleButtonChange(this);

或者你可以像这样声明你的方法

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

根本不使用 bind

答案 1 :(得分:0)

在grandParent组件中,您应该通过关键字bind将其绑定到当前组件以通过props传递它。 this.handleButtonChange = this.handleButtonChange.bind(this);