【问题标题】:React Native using setState with setParamsReact Native 使用 setState 和 setParams
【发布时间】:2018-02-23 22:25:32
【问题描述】:

我正在开发一个反应原生应用程序,我希望能够从静态导航选项更改状态。我在关注这个: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

如果有任何帮助,我将不胜感激。

【问题讨论】:

    标签: javascript react-native


    【解决方案1】:

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

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

    constructor(props) {
      super(props);
    
      this.openCreateModal = this.openCreateModal.bind(this);
    }
    

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 2019-09-10
      • 2021-05-18
      • 1970-01-01
      • 2020-06-11
      • 2018-01-20
      • 1970-01-01
      • 2020-11-25
      • 1970-01-01
      相关资源
      最近更新 更多