Nisarg答案的更详细解释.
在构造函数中为KeyboardAvoidingView
创建一个键
constructor(props) {
this.state = {
keyboardAvoidingViewKey: 'keyboardAvoidingViewKey',
}
}
在键盘的will/did hide上添加侦听器(并在willUnmount中删除它)
import { KeyboardAvoidingView, Keyboard, Platform } from 'react-native'
componentDidMount() {
// using keyboardWillHide is better but it does not work for android
this.keyboardHideListener = Keyboard.addListener(Platform.OS === 'android' ? 'keyboardDidHide': 'keyboardWillHide', this.keyboardHideListener.bind(this));
}
componentWillUnmount() {
this.keyboardHideListener.remove()
}
更新keyboardHideListener
函数中的keyboardAvoidingViewKey
,每次都应该是一个新值(我使用了一个时间戳),并在呈现KeyboardAvoidingView
元素时使用这个键.
keyboardHideListener() {
this.setState({
keyboardAvoidingViewKey:'keyboardAvoidingViewKey' + new Date().getTime()
});
}
render() {
let { keyboardAvoidingViewKey } = this.state
return (
<KeyboardAvoidingView behavior={'height'} key={keyboardAvoidingViewKey} style={...}>
...
</KeyboardAvoidingView>
)
}
Note:
经过更深入的调查,我现在知道了为什么在更改密钥后会重新创建视图.
如果愿意,可以通过向App.js
文件中添加以下代码来监视这些已发送的消息:
import MessageQueue from 'react-native/Libraries/BatchedBridge/MessageQueue'
const spyFunction = (msg) => {
console.log(msg);
};
MessageQueue.spy(spyFunction);
如果这样做,您会在日志(log)中注意到,每次键更改时,作为返回发送的命令都是createViews
,如上所述,它会创建嵌套在所述组件下的所有元素.