React Native开发React Native学习React Native实践

ReactNative固定底部TextInput,解决键盘遮挡、

2018-11-12  本文已影响18人  FanChason

效果图

timer.gif

做类似于微信聊天输入框,可能会遇到下面三个小困扰,记录一下。

目录

# 1、ReactNative固定底部TextInput
# 2、键盘遮挡问题
# 3、列表滚动问题

困扰 1、ReactNative固定底部TextInput

react-native 没有fixed
核心方案:
- 最外部的包裹, flexDriction 默认的竖直
- 中间是滚动层 flex: 1,(ScrollView可以不加flex: 1, 其他组价没测试,)
- 最下面的组件 固定高度
<View style={flexDirection: 'column'}>
    <ScrollView>
        <Text>这是中间的滚动页面   (flex: 1)</Text>
        <Text>页面展示在这个组件中</Text>
    </ScrollView>
    <TextInput
            style={styles.inputView}
            returnKeyType="send"
            placeholder="请输入消息"
     />
</View>

困扰2、键盘遮挡问题

有多种方案:

最简单、最容易安装使用的方法是 KeyboardAvoidingView。这是一个核心组件,同时也非常简单。

你要做的第一件事是用 KeyboardAvoidView 替换 View,然后给它加一个 behavior 的 prop。查看文档的话你会发现,他可以接收三个不同的值作为参数 —— height, padding, position。我发现 padding 的表现是最在我意料之内的,所以我将使用它

    render () {
        return (
            <KeyboardAvoidingView
                style={styles.container}
                behavior="padding"
            >
                <FlatList
                    ref={'flatList'}
                    data={dataSources}
                    renderItem={this._renderItem}
                    // ItemSeparatorComponent={ItemDivideComponent}
                />
                <TextInput
                    style={styles.inputView}
                    returnKeyType="search"
                    placeholder="请输入消息"
                />
                <View style={{height: 20}}></View>
            </KeyboardAvoidingView>
        )
    }

下一种解决办法是使用 react-native-keyboard-aware-scroll-view,他会给你很大的冲击。实际上它使用了 ScrollViewListView 处理所有的事情(取决于你选择的组件),让滑动交互变得更加自然。它另外一个优点是它会自动将屏幕滚动到获得焦点的输入框处,这会带来非常流畅的用户体验。

它的使用方法同样非常简单 —— 只需要替换 基础代码View

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view'
<KeyboardAwareScrollView>
  <View>
    <TextInput />
  </View>
</KeyboardAwareScrollView>

这是迄今为止最为手动的方式,但也同时给开发者最大的控制权。你可以使用一些动画库来帮助实现之前看到的那种平滑滚动。
主要是监听键盘活动,主动做一些操作,
详见列表滚动问题处理

如果想提炼一些代码,我倾向于结合几种情况在一起。例如: 通选方案 1 和方案 3

困扰3、列表滚动问题

我的代码:

    componentWillMount () {
        this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
        this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
    }

    componentWillUnmount() {
        this.keyboardWillShowSub.remove();
        this.keyboardWillHideSub.remove();
    }

    keyboardWillShow = (event) => {
        this.refs.flatList.scrollToIndex({animated: true, index: this.generateBig().length-1, viewPosition: 0.5});
    };

    keyboardWillHide = (event) => {
        this.refs.flatList.scrollToIndex({animated: true, index: this.generateBig().length-1, viewPosition: 1.9})
    }

传送门

分享我的代码:# RNTextInput

参考:

1,react-native固定吸顶navBar和底部tabBar
2,困扰2后两种方案,以及详细方案参考:如何让你的 React Native 应用在键盘弹出时优雅地响应
3,React Native 踩坑日记(十) —— 使用 flatlist 的滚动处理键盘遮挡的问题.

上一篇下一篇

猜你喜欢

热点阅读