Javascript 道具处理器工作不一致?
我正在开发一个RN应用程序,遇到了一个问题,由于子组件中发生的事件,我试图更改组件的状态,结果不一致Javascript 道具处理器工作不一致?,javascript,reactjs,react-native,Javascript,Reactjs,React Native,我正在开发一个RN应用程序,遇到了一个问题,由于子组件中发生的事件,我试图更改组件的状态,结果不一致 var app = React.createClass({ render: function() { return ( <MainLogin onLogin={this.onLogin} /> ); }, onLogin: function() { this.setState({isLoggedIn: true}); } });
var app = React.createClass({
render: function() {
return (
<MainLogin onLogin={this.onLogin} />
);
},
onLogin: function() {
this.setState({isLoggedIn: true});
}
});
class MainLogin extends Component {
render() {
return(
<Login changeSomething={this.changeSomething} onLogin={this.props.onLogin}/>
);
}
changeSomething() {
this.setState({something: true});
}
}
class Login extends Component {
constructor(props) {
super(props);
}
loginPressed() {
this.props.onLogin(); //This works
}
changeSomething() {
this.props.changeSomething(); //This doesn't work
}
render() {
return (
<View style={{flex: 1}}>
<Button onPress={this.changeSomething.bind(this)}>Change Something</Button>
<Button onPress={this.loginPressed.bind(this)}>Login</Button>
</View>
);
}
}
var-app=React.createClass({
render:function(){
返回(
);
},
onLogin:function(){
this.setState({isLoggedIn:true});
}
});
类MainLogin扩展组件{
render(){
返回(
);
}
改变某物{
this.setState({something:true});
}
}
类登录扩展组件{
建造师(道具){
超级(道具);
}
登录压力(){
this.props.onLogin();//这很有效
}
改变某物{
this.props.changeSomething();//这不起作用
}
render(){
返回(
换东西
登录
);
}
}
onLogin函数运行良好,能够设置祖辈组件的状态,而changeSomething函数失败(this.setState不是函数)
有什么建议吗?您应该在ES6类中绑定组件方法。
React.createClass
会自动执行该操作,但是您的第二个和第三个组件是用ES6类进行子类化的。官方网站上有一个关于这个问题的报道。闻起来像是装订问题。。试试:changeSomething={this.changeSomething.bind(this)}
很好,这立刻就成功了。非常感谢。你知道为什么这是一个问题而不是另一个吗?啊,好的。这就解释了。谢谢