React NativeReactNativeReact Native实践

ReactNative键盘遮挡TextInput解决

2016-12-03  本文已影响6408人  BlainPeng

遇到的坑

本周工作中开发一个小任务,将TextInput放到屏幕最下面,然后在输入内容的时候键盘必须在TextInput的下方,此时就遇到了标题中所谈到的问题:键盘遮挡住了输入框。如下图:

KeyboardTextInput_1.gif

当时我开发完后我用的是Android机做的测试,发现在没有这种现象,但是在ios平台上却有。这对于产品来说是肯定不行的。刚开始问了一下其他同事有没有遇到这种问题,但他们也没有遇到过。只好求助Google了。搜了一下,别人也遇到了这种问题,现在把它记录一下。

解决方法

export default class KeyboardTextInputComponent extends Component {


    render() {

        return (

            <View style={styles.container}>

                <ScrollView
                    ref="scrollView"
                    style={{flex: 1}}
                >


                    <TextInput
                        ref="textInput"
                        style={styles.textInputStyle}
                        placeholder="请输入内容"
                        onBlur={this._reset.bind(this)}
                        onFocus={this._onFocus.bind(this, 'textInput')}
                    />
                </ScrollView>
            </View>

        );
    }

    _reset() {

        this.refs.scrollView.scrollTo({y: 0});

    }

    _onFocus(refName) {

        setTimeout(()=> {

            let scrollResponder = this.refs.scrollView.getScrollResponder();
            scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
                ReactNative.findNodeHandle(this.refs[refName]), 0, true);

        }, 100);
    }
}

通过上面操作,我们再来看一下效果图:

KeyboardTextInput_2.gif
上一篇 下一篇

猜你喜欢

热点阅读