React Native TextInput 键盘弹起方向问题

需求:进入ReactNative页面中,页面上含有TextInput控件,则TextInput 获取焦点,将键盘弹出需求。

问题:发现键盘有时候从右边滑出,好奇怪,键盘一般是从底边滑出呀!

我是利用页面刚渲染出来出现TextInput,在组件里根据autoFocus属性进行聚焦。

目前想到的原因是:页面是多次刷新的,可能页面还没渲染出来,键盘就跟着弹出来了,给人的感觉是键盘是从右边弹出的。

初始解决方法:

定义一个state,赋值给TextInput 的属性autoFocus,再componentDidMount里加个定时器,比如300ms 后改变状态,刷新页面。
结果:textInput没有聚焦。

后来查资料发现:autoFocus该属性如果为true,在componentDidMount后会获得焦点。默认值为false。设一个定时器去改变状态压根是不管用的,因为componentDidMount只走一遍呀。

接着查资料发现有个方法 focus(),可以认为设置textInput聚焦的。结合ref ,加定时器:

//this.amountTextInput textInput 引用
   if (this.amountTextInput) {
      if (!this.showPriceDirectly) {
        this.timer = setTimeout(() => {
          this.amountTextInput.focus();
          // this.setState({amountTextInputAutoFocus:!this.showPriceDirectly ? true : false})
        }, 80);
      }
    }

textInput 组件里就不要antoFocus属性了。

上面的方法算是解决了键盘从右边滑出的问题,但真正的原因,暂时还不知道,望大佬指点。

猜你喜欢

转载自blog.csdn.net/baihailing/article/details/89486672