我正在开发一个 react native 应用程序,我希望能够从静态导航选项更改状态。我正在关注这个:https://github.com/react-navigation/react-navigation/issues/1789
并实现了以下解决方案之一:
static navigationOptions = ({navigation}) => {
const { state } = navigation;
const {params = {}} = navigation.state;
navigation.params = {title: "", description: "", points: 0, image: {}, saveImage: true};
return {
headerRight: ( <Button transparent onPress={()=> params.create()}><Icon name="ios-add" style={{color: 'white'}}/></Button>)
};
};
componentDidMount() {
this.props.navigation.setParams({
create: this.openCreateModal
});
}
openCreateModal() {
this.setState({createModalVisible:true});
}
不幸的是,当我通过按下按钮调用 openCreateModal 函数时,收到错误 this.setState 不是函数
。
如果有任何帮助,我将不胜感激。
最佳答案
您的 openCreateModal()
方法未绑定(bind)。 Look further down在那个问题上有人指出了这个错误。
要解决此问题,您需要显式绑定(bind)它,以便它可以访问正确的 this
上下文,例如在构造函数中:
constructor(props) {
super(props);
this.openCreateModal = this.openCreateModal.bind(this);
}
或者您可以将其转换为 ES6 箭头函数,该函数会自动将其绑定(bind)到类的上下文,如下所示:
openCreateModal = () => {
this.setState({createModalVisible:true});
}
关于javascript - 使用 setState 和 setParams 来响应 Native,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48949893/