最近在开发RN时遇到这样一种状况,页面上方有个数字类型的输入框(keyboardType="numeric"),点开以后把页面底部的提交按钮给遮蔽了,可是IOS的数字键盘没有收缩功能,致使一点开就没法进行操做了,如图:html
所以须要在用户点击空白处时把键盘隐藏,能够使用以下的方法:react
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组件,所以想到了用高阶组件的实现方式:app
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#contentide
这样子就完成一个简单的高阶组件了。函数
使用方式有两种:flex
1.函数式ui
class FindPw extends Component { //...... } export default AutoHideKeyboard(FindPw)
2.decorator(装饰器)this
@AutoHideKeyboard class FindPw extends Component { //...... } export default FindPw
建议使用第二种,能够保证在之后叠加多个高阶组件时,不会出现 export defalut A(B(C(...)))这种难以解读的形式code