问题
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.
回答1:
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})
}
回答2:
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;}
来源:https://stackoverflow.com/questions/56167422/access-component-state-inside-navigationoptions-react-native