gpt4 book ai didi

javascript - KeyboardAvoidingView - 隐藏键盘时重置高度

转载 作者:IT王子 更新时间:2023-10-29 08:08:47 25 4
gpt4 key购买 nike

我正在使用 React Natives KeyboardAvoidingView 设置显示键盘时我的 View 的高度。但是,当我在应用程序中关闭键盘时,View 的高度并没有变回原来的值。

<KeyboardAvoidingView behavior="height" style={styles.step}>
<View style={styles.stepHeader}>
// my content
</View>
</KeyboardAvoidingView>

在我打开和关闭键盘之前,带有红色轮廓的 View 确实占据了整个空间。

Screenshot

最佳答案

关于Nisarg的更详细解释的答案。

KeyboardAvoidingView 创建 key 在构造函数中

constructor(props) {
this.state = {
keyboardAvoidingViewKey: 'keyboardAvoidingViewKey',
}
}

在键盘的 will/did 隐藏上添加监听器(并在 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()
}

更新keyboardAvoidingViewKeykeyboardHideListener函数,每次都应该是一个新值(我使用了时间戳)并在呈现 KeyboardAvoidingView 时使用此键元素。

keyboardHideListener() {
this.setState({
keyboardAvoidingViewKey:'keyboardAvoidingViewKey' + new Date().getTime()
});
}

render() {
let { keyboardAvoidingViewKey } = this.state
return (
<KeyboardAvoidingView behavior={'height'} key={keyboardAvoidingViewKey} style={...}>
...
</KeyboardAvoidingView>
)
}

注意:请记住,这将重新创建 KeyboardAvoidingView 中的元素。 (即:将调用他们的 constructor 函数,我不太清楚为什么,我会在深入调查后更新答案),所以你必须跟踪任何可能被覆盖的状态/ Prop 值

更新

经过更深入的调查,我现在知道为什么在更改 key 后会重新创建 View 。要想真正理解为什么会这样,必须要熟悉react-native是如何将render commands派发到native端的,这个具体解释比较长,感兴趣的可以看看我的回答here .简而言之,react-native 使用 Reactjs 来比较应该呈现的变化,然后将这些差异作为命令发送到名为 UIManager 的组件。 ,它发送转换为布局树的命令式命令,布局树根据 diff 命令更改布局。一旦你在一个组件上设置了一个键,reactjs 就使用这个键来识别对所述组件的更改,如果这个键发生变化,reactjs 将该组件识别为一个全新的组件,作为返回发送初始命令来创建所述组件,使其成为从头开始创建子项,因为在新布局树中有新元素被识别,删除旧树并创建新树而不是仅仅调整差异

如果您愿意,您实际上可以通过将以下代码添加到您的 App.js 来监视这些发送的消息文件:

import MessageQueue from 'react-native/Libraries/BatchedBridge/MessageQueue'
const spyFunction = (msg) => {
console.log(msg);
};

MessageQueue.spy(spyFunction);

如果这样做,您会在日志中注意到每次 key 更改时,返回的命令是 createViews ,如上所述,它创建了嵌套在所述组件下的所有元素。

关于javascript - KeyboardAvoidingView - 隐藏键盘时重置高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41616457/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com