我试图通过道具传递内置的function函数,并试图设置状态,但是我得到了未定义的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"} )我的问题是,每当我传递一个内置函数(即,react this中的函数总是未定义)。
如何通过道具发送内置函数?
发布于 2016-06-10 11:02:44
熟悉this和传递函数非常常见的问题。
tl;博士为了在this上调用setState,需要在需要更新状态的组件中调用this。你把它称为组件之外的。
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-10 11:02:45
ReactDom.render(<someComponent body={<someOtherComponent1 yourFn={somefun}/>} />, document.getElementById('someValidID'));和内部组件
this.props.yourFn()https://stackoverflow.com/questions/37746189
复制相似问题