简易ReactNative高阶组件实现自动隐藏键盘功能

前端之家收集整理的这篇文章主要介绍了简易ReactNative高阶组件实现自动隐藏键盘功能前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近在开发RN时遇到这样一种情况,页面上方有个数字类型的输入框(keyboardType="numeric"),点开之后把页面底部的提交按钮给遮蔽了,但是IOS的数字键盘没有收缩功能,导致一点开就无法进行操作了,如图:

因此需要在用户点击空白处时把键盘隐藏,可以使用如下的方法

  1. const dismissKeyboard = require('dismissKeyboard')
  2. export default class Demo extends Component {
  3. render() {
  4. return (
  5. <TouchableWithoutFeedback onPress={dismissKeyboard}>
  6. <View style={{flex:1}}>
  7. //some components like TextInput
  8. </View>
  9. </TouchableWithoutFeedback>
  10. )
  11. }
  12. }

但每次都需要麻烦地引入dismissKeyboard和TouchableWithoutFeedback组件,因此想到了用高阶组件的实现方式:

  1. const dismissKeyboard = require('dismissKeyboard')
  2. export default (WrappedComponent) => class AutoHideKeyboard extends Component {
  3. render() {
  4. return (
  5. <TouchableWithoutFeedback style={{flex:1}} onPress={dismissKeyboard}>
  6. <View style={{flex:1}}>
  7. <WrappedComponent {...this.props}/>
  8. </View>
  9. </TouchableWithoutFeedback>
  10. )
  11. }
  12. }

注意:即使你的WrappedComponent是一个用View包裹的组件,也得在TouchableWithoutFeedBack中再包一层View,才不会导致找不到setNativeProps的错误,详见:http://reactnative.cn/docs/0.40/direct-manipulation.html#content

这样子就完成一个简单的高阶组件了。

使用方式有两种:

1.函数

  1. class FindPw extends Component {
  2. //......
  3. }
  4. export default AutoHideKeyboard(FindPw)

2.decorator(装饰器)

  1. @AutoHideKeyboard
  2. class FindPw extends Component {
  3. //......
  4. }
  5. export default FindPw

建议使用第二种,可以保证在以后叠加多个高阶组件时,不会出现 export defalut A(B(C(...)))这种难以解读的形式

猜你在找的React相关文章