简体   繁体   中英

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. I was following this: 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 .

I'd appreciate any help with this.

Your openCreateModal() method is not bound. 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:

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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