加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 07:36:55 所属栏目:百科 来源:网络整理
导读:最近在开发RN时遇到这样一种情况,页面上方有个数字类型的输入框(keyboardType="numeric"),点开之后把页面底部的提交按钮给遮蔽了,但是IOS的数字键盘没有收缩功能,导致一点开就无法进行操作了,如图: 因此需要在用户点击空白处时把键盘隐藏,可以使用如

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

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

const dismissKeyboard = require('dismissKeyboard')
export default class Demo extends Component {
    render() {
        return (
            <TouchableWithoutFeedback onPress={dismissKeyboard}>
                <View style={{flex:1}}>
                   //some components like TextInput
                </View>
            </TouchableWithoutFeedback>
        )
    }
}

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

const dismissKeyboard = require('dismissKeyboard')
export default (WrappedComponent) => class AutoHideKeyboard extends Component {
    render() {
        return (
            <TouchableWithoutFeedback style={{flex:1}} onPress={dismissKeyboard}>
                <View style={{flex:1}}>
                    <WrappedComponent {...this.props}/>
                </View>
            </TouchableWithoutFeedback>
        )
    }
}

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

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

使用方式有两种:

1.函数式

class FindPw extends Component {
   //......
}
export default AutoHideKeyboard(FindPw)

2.decorator(装饰器)

@AutoHideKeyboard
class FindPw extends Component {
   //......
}
export default FindPw

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读