反应导航-如何在标题NavigationOptions中使用this.state?

fli*_*lix 2 react-native react-navigation

我已经花了几个小时在中找到处理状态的代码navigationOptions,但是直到现在我还不明白,

我有一个代码:

static navigationOptions = ({ navigation }) => {
    const { params = {} } = navigation.state
    return {
      headerLeft: <FontAwesome name='arrow-left' size={20} color="#FFF" onPress={() => navigation.navigate('Home')} style={{margin: DeviceWidth*0.04}}/>,
      // here I want to show the TextInput if the `HeaderRight pressed` and show the `String` for the first time
      headerTitle: this.state.showSearch ? <TextInput
        placeholder="this is placeholder"
        placeholder="search"
        underlineColorAndroid='transparent'
        placeholderTextColor= 'gray'
        minWidth={DeviceWidth*0.75}
        style={{borderWidth:1, borderColor:'grey', backgroundColor:'white', borderRadius:50}}
      /> : 'My Patient',
      // Here I want to set the state of `showSearch` to visible at `onPress`
      headerRight: <FontAwesome name='search' size={20} color="#FFF" onPress={() => params.handleRemove()} style={{margin: DeviceWidth*0.04}}/>,
    }
  }

  componentDidMount () {
    this.props.navigation.setParams({ handleRemove: this.removeVehicle })
  }

  removeVehicle = () => {
    this.setState({showSearch: !this.state.showSearch})
  }
  constructor(props){
    super(props); 
    this.state = {showSearch: false}
  }
Run Code Online (Sandbox Code Playgroud)

运行代码时出现错误

TypeError:undefined不是对象(评估'_this3.state.showSearch')

可以显示/隐藏headerTitle取决于this.state.showSearch

Pri*_*dya 10

您可以通过以下简单方法进行操作

 static navigationOptions =  ({ navigation }) => {
        const { params = {} } = navigation.state
       return {
            headerTitle: params.showSearch ? 'New Title' : 'Alternate Title'
            // Similarly for the rest
       }  
    }

changeTitle = () => {
   const {showSearch} = this.state
        // Assuming you have access to the navigation props
        this.props.navigation.setParams({
            showSearch
        })
   this.setState({showSearch: !showSearch})
 }
Run Code Online (Sandbox Code Playgroud)