NavigationOptions中的访问组件状态-React Native

时间:2019-05-16 11:22:36

标签: react-native react-navigation

我试图按状态值有条件地呈现HeaderLeft,但是我无法在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>

});

我的组件确实安装了

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

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

我的构造函数

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

  }
}

请让我知道如何解决此问题。

2 个答案:

答案 0 :(得分:0)

导航是静态的,这就是为什么它不访问状态。 如果要导航器更新状态,则每次更新状态时都需要调用setparams。我会创建一个函数来更新状态并更轻松地调用setparams。

updateNavAndState(bool){
    this.props.navigation.setParams({
        searchText: bool,
      });
    this.setState({threebool:bool})
}

答案 1 :(得分:0)

this.props.navigation.setParams({
  handleSubmit: this.handleSubmit,
  state: this.state;
});
handleSubmit = () => {}

在导航选项中,您将获得值

static navigationOptions = ({ navigation = this.props.navigation }) => {
const state = navigation.state.params.state;
const handleSubmit = navigation.state.params.handleSubmit;}