0

我正在尝试通过道具传递内置的反应功能并尝试设置状态,但我得到this了未定义的!

我试过这样的事情:

index.js

let somefun = function(){
    this.setState({myvar:1});
}

ReactDom.render(<someComponent body={<someOtherComponent1 componentWillUpdate={somefun}/>} />, document.getElementById('someValidID'));

someOtherComponent1.js

React.createElement( someOtherComponent1, { "className": "someclass"} )

我的问题是每当我传递一个内置函数时,即反应原型this中存在的函数总是未定义的。

如何通过 props 发送内置函数?

4

2 回答 2

1

this熟悉和传递函数的非常常见的问题。

tl;dr为了调用setStateon thisthis需要在需要更新其状态的组件内部调用。您在组件之外调用它。

someFun是一个新函数,它调用其中的一个函数this。问题在于,在这种情况下,this是对组件实例的引用,someFun而不是您的组件实例。来吧,放一个console.log(this)在那里看看。

我认为在您的场景中onComponentWillUpdate应该是组件内部的一个函数,而不是在它之外声明。

render: function() {
  return (
    <someOtherComponent1 onComponentWillUpdate={function(nextProps, nextState) {
       // do something here
      }}
    />
  )

但是,不要忘记您必须在子组件中实际调用该函数。

// in someOtherComponent1
componentWillUpdate: function(nextProps, nextState) {
  // do something
  this.props.onComponentWillUpdate(nextProps, nextState)
}
于 2016-06-10T11:02:44.060 回答
0
ReactDom.render(<someComponent body={<someOtherComponent1 yourFn={somefun}/>} />, document.getElementById('someValidID'));

和内部组件

this.props.yourFn()
于 2016-06-10T11:02:45.033 回答