使用setState与setParams反应Native

时间:2018-02-23 14:18:31

标签: javascript react-native

我正在开发一个本机应用程序,我希望能够从静态navigationOptions更改状态。我跟着这个: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 is not a function

我很感激任何帮助。

1 个答案:

答案 0 :(得分:1)

您的openCreateModal()方法未受约束。 Look further down在那个问题上,有人指出了这个错误。

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

constructor(props) {
  super(props);

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

或者您可以将其转换为ES6箭头函数,该函数会将其自动绑定到类的上下文中,如下所示:

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