最近在开发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(...)))这种难以解读的形式