Access Component state inside NavigationOptions -

2019-08-24 11:19发布

I was trying to conditionally render HeaderLeft by state value, I cant able to access state value inside NavigationOptions

 static navigationOptions = ({ navigation }) => ({



    headerLeft: (navigation.state.searchText)? <View style={{ flexDirection: 'row', justifyContent: 'center' }}>

        <TouchableOpacity onPress={() => {
           // navigation.navigate('home');
           alert('Coming soon ');
        }}>
            <Image style={{ marginLeft: 20,height:20,width:20,resizeMode:"contain" }} source={require('../assets/header_icons/three_logo.png')} />
        </TouchableOpacity>
    </View> : <View style={{ flexDirection: 'row', justifyContent: 'center' }}>

<TouchableOpacity onPress={() => {
   // navigation.navigate('home');
   alert('Coming soon');
}}>
    <Image style={{ marginLeft: 20,height:20,width:20,resizeMode:"contain" }} source={require('../assets/header_icons/icon_arrow_left.png')} />
</TouchableOpacity>
</View>

});

My component did mount

  componentDidMount(){
  this.setState({threebool:true});
  this.props.navigation.setParams({

    searchText: this.state.threebool,
  });
}

My constructor

constructor(props) {
  super(props)
  this.state = {
    threebool:true,

  }
}

Please let me know how to resolve this.

2条回答
不美不萌又怎样
2楼-- · 2019-08-24 11:48
this.props.navigation.setParams({
  handleSubmit: this.handleSubmit,
  state: this.state;
});
handleSubmit = () => {}

in navigation option you will get values by

static navigationOptions = ({ navigation = this.props.navigation }) => {
const state = navigation.state.params.state;
const handleSubmit = navigation.state.params.handleSubmit;}
查看更多
Explosion°爆炸
3楼-- · 2019-08-24 11:53

Navigation is static, that`s why it doens't access state. if you want your navigator to update with your state you need to call setparams everytime you update state. I would create a function to update state and call setparams to it easier.

updateNavAndState(bool){
    this.props.navigation.setParams({
        searchText: bool,
      });
    this.setState({threebool:bool})
}
查看更多
登录 后发表回答