React Navigation - 如何在Header navigationOptions中使用this.state?

时间:2018-04-06 06:19:00

标签: 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}
  }

当我运行代码时,我有一个错误

  

TypeError:undefined不是对象(评估&#39; _this3.state.showSearch&#39;)

可以根据this.state.showSearch显示/隐藏headerTitle吗?

1 个答案:

答案 0 :(得分:5)

您可以通过以下简单方式执行此操作

 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})
 }