2016-11-07 50 views
1

获取不是一个函数(或),如果我绑定我得到绑定的未定义的错误,我应该如何绑定这样的函数传递一个值?我在这里错过什么..?需要帮助。不是一个函数和绑定的未定义的错误reactjs

子组件:

constructor(props) { 
     super(props); 
     this.handler = this.handler.bind(this); 
      this.state = { 
      isBoolFlag: true, 
     } 
     } 

     onClick(e){ 
     this.setState({ 
      isBoolFlag: !this.state.isBoolFlag, 
     }); 
     this.props.handler(!this.state.isBoolFlag); //Error here.. 

     } 

     render() { 
     return (
      <div> 
       <a onClick={this.onClick.bind(this)}> 
      </div> 
     ); 
     } 
    } 

父组件:

constructor(props) { 
    super(props); 
    this.handler = this.handler.bind(this); 
    this.state = { 
     showModule: false, 
    }; 
    } 

<div> 
{this.state.showModule ? <Child2 /> : <Child1 handler={this.handler} />} 
      </div> 

回答

0

你不需要在子组件this.handler = this.handler.bind(this);。函数handler必须是父级中定义的函数。

另外,要小心:

this.setState({ 
      isBoolFlag: !this.state.isBoolFlag, 
     }); 
this.props.handler(!this.state.isBoolFlag); //Error here.. 

使用此代码你不能依靠isBoolFlag被改变在该州handler之前被称为,因为是的setState异步。你应该发送一个回调函数作为setState的第二个参数。

+0

感谢您的回复。我已经在Parent中定义了,但是我仍然得到了错误this.props。处理程序不是函数(...)。感谢您指出,我也刚刚意识到setState不会立即反映出来。 – monkeyjs

+0

没问题:)你能否在你的问题中添加Parent的组件代码或者至少是函数的代码? –

+0

我已经添加了家长的组件代码也问题,让我知道如果你不能看到它..只是再次更新问题http://stackoverflow.com/users/6499571/c%c3%a9sar-landesa – monkeyjs

0

您需要在setState中使用回调函数,因为setState需要一些时间来改变状态并且javascript是异步的,所以this.state.isBookFlag仅用于其以前的状态。

使用它像

this.setState({ 
      isBoolFlag: !this.state.isBoolFlag, 
     }, function(){ 
     this.props.handler(!this.state.isBoolFlag); 
}); 

你也只需要处理函数绑定在父组件,而不是在子组件

典子组件。

constructor(props) { 
    super(props); 

     this.state = { 
     isBoolFlag: true, 
    } 
    } 

    onClick(e){ 
    this.setState({ 
      isBoolFlag: !this.state.isBoolFlag, 
     }, function(){ 
     if(this.props.handler !== undefined) { 
     this.props.handler(!this.state.isBoolFlag); 
     } 
    }); 

    } 

    render() { 
    return (
     <div> 
      <a onClick={this.onClick.bind(this)}> 
     </div> 
    ); 
    } 
} 

家长:

constructor(props) { 
    super(props); 
    this.state = { 
     showModule: false, 
    }; 
    } 

<div> 
{this.state.showModule ? <Child2 /> : <Child1 handler={this.handler.bind(this)} />} 
      </div> 
+0

是的,我有它在父组件已经 - 但仍然是相同的错误... ... http://stackoverflow.com/users/5928186/shubham-khatri – monkeyjs

+0

@monkeyjs您正在创建一个儿童组件的基础上,因此在小孩你需要在调用它之前检查处理函数是否被定义。查看更新的代码 –

0

更新:

我错过了通过处理程序组件,就像我做了。