【问题标题】:Hide a component on React Native on pressing Back button在按下返回按钮时隐藏 React Native 上的组件
【发布时间】:2019-04-09 21:54:05
【问题描述】:

我试图在按下硬件返回键时隐藏一个子组件。

这是我到目前为止所做的:

render(){

     return(
            <View > 
               <TouchableOpacity onPress={()=> this.onTypePress('cuisine')}> 
                 <Text>Cuisines</Text> 
               </TouchableOpacity>
               {this.renderFilterType()}    
            </View>
           );
     }

     renderFilterType(){
        if(this.props.showFilterByType){
          return <FilterByType />
        }
     }

this.props.showFilterByType 是我通过 Redux 设置的布尔值。

onTypePress 会触发 Redux 状态。

我正在按下返回按钮 像这样按下FilterByType

constructor(props){
    super(props)
     this.handleBackButtonClick= this.handleBackButtonClick.bind(this)
}
handleBackButtonClick(){
       this.props.hideFilterByType(' ')
        BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick);
      }
componentDidMount(){
      BackHandler.addEventListener('hardwareBackPress', 
      this.handleBackButtonClick);
    }

当我单击后退按钮时,它会返回到上一个按钮,但一秒钟后它也会关闭应用程序(第一个屏幕)。

当我从 FilterByType.js 中删除 BackHandler.removeEventListener('hardwareBackPress', this.handleBackButtonClick); 时,后退按钮在整个应用程序中停止工作。

有什么我做错的建议吗??!!

【问题讨论】:

  • 后退按钮事件监听器是否仅在您的子组件上?
  • 是的!只在我的孩子比赛@JRK
  • 那么,在您第二次单击时(当您的子组件已卸载时)您没有后退按钮监听器?我假设您不想退出应用程序?
  • 是的!顺便说一句,我能够解决它。检查我的答案,如果它满足。 @JRK

标签: react-native


【解决方案1】:

来自React-native BackHandler Documentation

Android:检测硬件后退按钮按下,如果没有侦听器或如果没有侦听器返回 true,则以编程方式调用默认的后退按钮功能以退出应用程序。

因此我将 handleBackButtonClick() 编辑为:

 handleBackButtonClick(){
   this.props.hideFilterByType(' ')
   BackHandler.removeEventListener('hardwareBackPress',this.handleBackButtonClick);
   return true
 }

【讨论】:

    猜你喜欢
    • 2017-01-19
    • 1970-01-01
    • 2021-03-21
    • 1970-01-01
    • 2020-09-26
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多