如何在 React Native 的导航项中使用状态变量

How to use status variable in navigation item in React Native

我想 show/hide 根据 React Native 应用程序中的状态变化导航项目。 这就是我所做的。

static navigationOptions = ({ navigation }) => {    
    return {
      headerLeft: <Button this.state.showSaveBtn && title='Save'/>
    }
  }
...
validateForm () {
    if (validate()){
       this.setState({showSaveBtn: true});
    } else {
       this.setState({showSaveBtn: false});
    }
}

但它不能是 运行 因为 'this' 不引用当前组件。 我刚刚展示了我想怎么做。 重要的是用状态变量控制导航项。

谢谢。

改变想法

navigationOptions: {
    header: null
}

自定义一个header

您需要设置导航状态,而不是组件状态。 如果表单 validate() returns 为真,您可以执行类似 this.props.navigation.setParams({showSaveBtn: true }) 的操作,然后在导航选项中您只需要执行以下操作:

static navigationOptions = ({ navigation }) => {

        const { params } = navigation.state;

        return {
          headerLeft: <Button params.showSaveBtn && title='Save'/>
        }

};

Ps.: 不要忘记在componentWillMount()

中定义showSaveBtn导航参数的默认值