我在我的应用程序中使用React-Navigation,该应用程序包含多个屏幕的StackNavigator,其中一些屏幕具有带有autoFocus={true}
的TextInput
问题:在组件渲染时在这些屏幕上,屏幕的高度在构造函数中设置:
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之外,还有其他方法可以解决这个问题吗?
这就是我做的:
如果应用程序具有“授权/登录/注册屏幕”,则:
this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow);
this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide);
_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 });