编程语言
首页 > 编程语言> > javascript – 如何在React-Native中获得键盘的高度?

javascript – 如何在React-Native中获得键盘的高度?

作者:互联网

我在我的应用程序中使用React-Navigation,应用程序包含多个屏幕的StackNavigator,其中一些屏幕具有带有autoFocus的TextInput = {true}

问题:在组件渲染时在这些屏幕上,屏幕的高度在构造函数中设置:

constructor(props) {
    super(props);
    this.state = { 
        height: Dimensions.get('window').height,
    };
}

但是,由于TextInput的autoFocus为true,因此在渲染后,屏幕上的键盘几乎立即弹出,导致组件重新渲染,因为在componentWillMount中添加到Keyboard的eventListener:

 componentWillMount() {
    this.keyboardWillShowListener = Keyboard.addListener(
        "keyboardWillShow",
        this.keyboardWillShow.bind(this)
    );
}

keyboardWillShow(e) {
    this.setState({
        height:
            Dimensions.get("window").height * 0.9 - e.endCoordinates.height
    });
    LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
}

这会影响性能,我希望避免不必要的重新渲染.

问题:
1.是否可以在React-Navigation的ScreenProps中设置键盘的动态高度(取决于设备)?
2. React-Navigation的state.params是否可以这样做?
3.除了应用KeyboardAvoidingView或this module之外,还有其他方法可以解决这个问题吗?

解决方法:

这就是我做的:

如果应用程序具有“授权/登录/注册屏幕”,则:

>在componentWillMount中添加KeyboardListeners,如here所述:

this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);

>将autoFocus添加到电子邮件/电话号码/页面上的任何其他“第一个”TextInput,以便在屏幕加载时弹出键盘.
>在_keyboardDidShow函数中,用作KeyboardListener,执行以下操作:

_keyboardDidShow(e) {
    this.props.navigation.setParams({
        keyboardHeight: e.endCoordinates.height,
        normalHeight: Dimensions.get('window').height, 
        shortHeight: Dimensions.get('window').height - e.endCoordinates.height, 
    }); 
}

Dimensions是React-Native的API,不要忘记导入它就像导入任何React-Native组件一样.
>之后,在重定向到下一页时,传递这些参数,不要忘记继续将它们传递到其他屏幕,以免丢失这些数据:

this.props.navigation.navigate('pageName', { params: this.props.navigation.state.params });

标签:react-navigation,javascript,react-native,keyboard
来源: https://codeday.me/bug/20190930/1835272.html