提供个输入框在底部时候可以自动跟随键盘的高阶组件



  • 效果

    0_1460574666902_IMG_0027.png

    代码

    /**
     * Created by wjx on 16/4/11.
     */
    import React, {
        Component,
        View,
        Dimensions,
        DeviceEventEmitter,
        LayoutAnimation,
    } from 'react-native';
    
    const SCREEN_HEIGHT = Dimensions.get('window').height;
    
    /**
     * 高阶函数,用于给需要键盘输入的视图提供整个视图的高度控制.
     *
     * 键盘出现的时候将视图高度缩小,去掉键盘的高度,隐藏则反之.
     *
     * @param WrappedComponent
     */
    export default function (WrappedComponent) {
        return class extends Component {
    
            state = {
                visibleHeight: SCREEN_HEIGHT,
            };
    
            componentWillMount() {
                DeviceEventEmitter.addListener('keyboardWillShow', this._onKeyboardWillShow);
                DeviceEventEmitter.addListener('keyboardWillHide', this._onKeyboardWillHide);
            }
    
            componentWillUnmount() {
                DeviceEventEmitter.removeAllListeners('keyboardWillShow');
                DeviceEventEmitter.removeAllListeners('keyboardWillHide');
            }
    
            _onKeyboardWillShow = (e) => {
    
                const visibleHeight = SCREEN_HEIGHT - e.endCoordinates.height;
                LayoutAnimation.configureNext(LayoutAnimation.create(
                    e.duration,
                    LayoutAnimation.Types[e.easing]
                ));
    
                this.setState({
                    visibleHeight
                });
            };
    
            _onKeyboardWillHide = () => {
    
                this.setState({
                    visibleHeight: SCREEN_HEIGHT,
                });
            };
    
            render() {
                return (
                    <View
                        style={{height: this.state.visibleHeight}}
                    >
                        <WrappedComponent {...this.props} />
                    </View>
                );
            }
    
        };
    }
    
    

登录后回复