【发布时间】:2016-02-23 17:57:14
【问题描述】:
我正在开发一个 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 函数运行完美,能够设置祖父组件的状态,而 changeSomething 函数失败(this.setState 不是函数)。
有什么建议吗?
【问题讨论】:
-
闻起来像绑定问题..尝试:
changeSomething={this.changeSomething.bind(this)} -
嗯,这立即奏效了。谢谢你。你知道为什么这会是一个问题而不是另一个问题吗?
标签: javascript reactjs react-native