我正在开发 RN 应用程序,但遇到了一个问题:由于子组件中发生的事件,我尝试更改组件的状态,但得到的结果不一致。
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>
);
}
}
onLogin 函数运行完美,并且能够设置 Grandparent 组件的状态,而 changeSomething 函数失败(this.setState 不是函数)。
有什么建议吗?
最佳答案
您应该绑定(bind) ES6 类中的组件方法。React.createClass
自动执行此操作,但您的第二个和第三个组件是 ES6 类的子类。这是一个explanation官方网站上有相关内容。
关于javascript - Prop 处理程序不能一致工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35584797/