簡體   English   中英

反應父子通信:TypeError:_this.state.myFunction 不是函數

[英]React parent-child communication: TypeError: _this.state.myFunction is not a function

我是 React 世界的新手,我正在嘗試使用應該從子組件調用的函數來構建父組件。 但是,當我調用該函數時,我在標題中收到錯誤消息。 我有類似的東西:

 class ParentComponent extends React.Component { constructor(props) { super(props); this.myFunction = this.myFunction.bind(this); } myFunction(param) { //do something } render(){ return( <ChildComponent event={this.myFunction} /> ); } } class ChildComponent extends React.Component { constructor(props) { super(props); this.state = { inheritedFunction: this.props.event }; } childFunction(param) { //do a few things first this.state.inheritedFunction(param); } render(){ return( <input type="checkbox" onChange={this.childFunction.bind(this)></input> ); } }

我的代碼編譯並運行,然后當它在選中復選框時執行 childFunction() 時,this.state.inheritedFunction(param) 說它不是一個函數,應用程序崩潰。 我懷疑它必須與綁定做一些事情,但我真的不確定並堅持這個問題。

我是 React 的新手,所以請保持友善。 :-) 有誰知道我搞砸了什么?

class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.myFunction = this.myFunction.bind(this);
  }

  myFunction = (param) => {
    //do something  
    alert(param);
  }

  render(){
    return(
      <ChildComponent event={this.myFunction} />
    );
  }
 }


 class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      inheritedFunction: this.props.event
    };
  }

  childFunction(param) {
    //do a few things first
    this.props.event(param);
  }

  render(){
    return(
     <input type="checkbox" onChange={this.childFunction.bind(this)></input>
    );
  }  
 }

我認為您的問題是嘗試在狀態內保存引用,然后在 onchange 回調中再次綁定該函數。

刪除構造函數上的state ,直接從props調用它

 class ParentComponent extends React.Component { constructor(props) { super(props); this.myFunction = this.myFunction.bind(this); } myFunction(param) { //do something } render(){ return( <ChildComponent event={this.myFunction} /> ); } } class ChildComponent extends React.Component { constructor(props) { super(props); this.childFunction = this.childFunction.bind(this); // bind on the constructor. } childFunction() { //do a few things first this.props.event(this) //call the prop directly here. } render(){ return( <input type="checkbox" onChange={this.childFunction></input> // no more binding here ); } }

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

  myFunction = param => {
    //do something
  };

  render() {
    return <ChildComponent event={this.myFunction} />;
  }
}

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

  childFunction = (param) => {
    //do a few things first
    this.props.event(param);
  }

  render() {
    return <input type="checkbox" onChange={this.childFunction} />
  }
}

暫無
暫無

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

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