相关疑难解决方法(0)

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

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

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

constructor(props) {
    super(props);
    this.state = { 
        height: Dimensions.get('window').height,
    };
}
Run Code Online (Sandbox Code Playgroud)

但是,由于autoFocusTextInput是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);
}
Run Code Online (Sandbox Code Playgroud)

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

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

javascript keyboard react-native react-navigation

29
推荐指数
4
解决办法
2万
查看次数