问题描述
我在我的应用程序中使用React-Navigation,该应用程序包含多个屏幕的StackNavigator,其中一些屏幕的TextInput为 autoFocus = {true}
I am using React-Navigation in my app and the app consists of StackNavigator with multiple screens, some screens of which have TextInput with autoFocus={true}
问题:当组件渲染时,这些屏幕上的高度是在构造函数中设置的:
Problem: on these screens when the component renders, the height of the screen is being set in the constructor:
constructor(props) {
super(props);
this.state = {
height: Dimensions.get('window').height,
};
}
但是,因为 autoFocus
of TextInput是 true
,屏幕上的键盘几乎立即弹出渲染后,导致组件重新出现由于在componentWillMount中添加到键盘的eventListener而渲染:
But, since the autoFocus
of TextInput is true
, the keyboard on this screen pops-up on the screen almost instantly after the render, causing the component to re-render due to the eventListener that is added to Keyboard in componentWillMount:
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);
}
这会影响性能,我希望避免不必要的重新渲染。
This affects the performance and I would like to avoid the unnecessary re-renders.
问题:
1.是否可以设置键盘的动态高度(取决于设备)在React-Navigation的ScreenProps中?
2.是否可以使用React-Navigation的state.params进行相同操作?
3.有没有其他方法可以解决这个问题,除了应用KeyboardAvoidingView或?
推荐答案
这就是我所做的:
如果应用有授权/登录 /注册屏幕然后:
If the app has "Authorization / Log-in / Sign-up screen" then:
-
在componentWillMount中添加KeyboardListeners,如解释:
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
添加到页面上的电子邮件/电话号码/任何其他第一TextInput,以便在屏幕加载时,键盘弹出 -
Add autoFocus to e-mail / phone number / any other "first" TextInput on the page, so that when the screen loads, the Keyboard pops-up.
在 _keyboardDidShow
函数中,用作KeyboardListener,执行以下操作:
In _keyboardDidShow
function, that is used as a KeyboardListener, do the follows:
_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组件一样。
Dimensions is an API of React-Native, do not forget to import it just like you import any React-Native component.
之后,在重定向到下一页时,传递这些参数并不要忘记继续将它们传递到其他屏幕,以免丢失这些数据:
After that, while redirecting to the next page, pass these params and do not forget to keep on passing them to other screens in order not to lose this data:
this.props.navigation.navigate('pageName', { params: this.props.navigation.state.params });
这篇关于如何在React-Native中获得键盘的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!