我如何在React Native中检查navigationOptions内部的条件

时间:2018-11-20 07:09:59

标签: react-native

我想设置自定义导航headerLeft属性;仅在满足条件的情况下才能设置headerLeft属性,否则不行。我在应用程序中使用StackNavigator。并且也无法从navigationOptions内部访问道具。

这是我的代码

componentDidMount() {
 this.props.navigation.setParams({goBack: this.goBack, shouldShow: this.state.show });
}


onShow = () => {
  if (this.state.steps >1) {
    this.setState({show:true}, () => {this.props.navigation.setParam({shouldShow:true})} )
  }
}
goBack= () =>{
 this.setState({ steps: this.state.steps - 1 })
}


static navigationOptions = ({ navigation }) => {
  const { params = {} } = navigation.state;
  let headerLeft = null;
  if (params.shouldShow) {
    headerLeft = <TouchableOpacity onPress={() => params.goBack}>
      <Image source={/* src */} style={Styles.navBarIcon} />
    </TouchableOpacity>
  }

  return {
    headerLeft: headerLeft,
    headerTitle: 'Register',
    headerStyle: Styles.navBar,
  };
};

1 个答案:

答案 0 :(得分:2)

由于导航选项是静态的,并且不包含在类中,因此您不能简单地访问其内部的状态。但是您可以按照以下方法进行操作。

// ------ inside your class -------

static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state;
    let headerLeft = null;
    if(params.shouldShow) {
    headerLeft = <TouchableOpacity onPress={() => params.onPressButton()}>
                     <Image source={/* source */} style={Styles.navBarIcon} />
                  </TouchableOpacity>
    }

    return {
        headerLeft: headerLeft
    };
};

componentDidMount(){
    this.props.navigation.setParams({ onPressButton: this.onButtonPressedEvent, shouldShow:this.state.show });
}

onButtonPressedEvent = () =>{
// What you want to do when button pressed.
}

onShow = () =>{
   if(this.state.count > 1){
       this.setState({show:true}, () => {this.props.navigation.setParam({shouldShow:true})} )
   }
}

请记住在更改计数以更改导航时调用onShow方法。