简体   繁体   English

使用setState与setParams来反应Native

[英]React Native using setState with setParams

I'm working on a react native app where I'd like to be able to change the state from the static navigationOptions. 我正在开发一个React本机应用程序,我希望能够从静态NavigationOptions更改状态。 I was following this: https://github.com/react-navigation/react-navigation/issues/1789 我正在关注: https : //github.com/react-navigation/react-navigation/issues/1789

And have implemented one of the solutions as follows: 并实现了以下解决方案之一:

 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}); } 

Unfortunately when I call the openCreateModal function by pressing the button, I get the error this.setState is not a function . 不幸的是,当我通过按下按钮调用openCreateModal函数时,出现错误this.setState is not a function

I'd appreciate any help with this. 我将不胜感激。

Your openCreateModal() method is not bound. 您的openCreateModal()方法未绑定。 Look further down in that issue and someone points out that mistake. 在这个问题上往下看 ,有人指出了这个错误。

To fix this, you either need to explicitly bind it so it has access to the correct this context, for example in your constructor: 要解决此问题,您需要显式绑定它,以便它可以访问正确的this上下文,例如在构造函数中:

constructor(props) {
  super(props);

  this.openCreateModal = this.openCreateModal.bind(this);
}

Or you can convert it to an ES6 arrow function which would auto-bind it to the class's context like so: 或者,您可以将其转换为ES6箭头函数,将其自动绑定到类的上下文,如下所示:

openCreateModal = () => {
  this.setState({createModalVisible:true});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM