簡體   English   中英

將道具傳遞給孫子 React

[英]Passing Props to grandchild React

孩子:

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一直傳遞給子項(這是一個按鈕),當按鈕被點擊時,它會觸發點擊事件,該事件觸發這個功能,在祖父組件中進行更改(即設置按鈕狀態)我哪里錯了或者這種方法完全錯誤我真的很陌生。 我只想通過子單擊事件在grandParent 中設置狀態。 我不斷收到此錯誤TypeError: this.props.handleButtonChange is not a function希望得到任何幫助

你的頂層組件有錯別字

它應該是

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

並不是

this.handleButtonChange = this.handleButtonChange(this);

或者,您可以像這樣聲明您的方法

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

根本不使用bind

在grandParent組件中,您應該通過關鍵字bind將其綁定到當前組件以將其傳遞給props。 this.handleButtonChange = this.handleButtonChange.bind(this);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM