使用setState与setParams反应Native [英] React Native using setState with setParams

查看:102
本文介绍了使用setState与setParams反应Native的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个本机应用程序,我希望能够从静态navigationOptions更改状态。我跟着这个: https://github.com/react-navigation/react -navigation / issues / 1789

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

不幸的是,当我按下按钮调用openCreateModal函数时,我收到错误 this.setState不是函数

Unfortunately when I call the openCreateModal function by pressing the button, I get the error this.setState is not a function.

我很感激任何帮助。

推荐答案

您的 openCreateModal()方法未绑定。在该问题上进一步了解并且有人指出那个错误。

Your openCreateModal() method is not bound. Look further down in that issue and someone points out that mistake.

要解决此问题,您需要显式绑定它,以便它可以访问正确的 this 上下文,例如在你的构造函数中:

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

或者你可以将它转换成ES6箭头函数,它会自动绑定它像这样的类的上下文:

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

这篇关于使用setState与setParams反应Native的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆