gpt4 book ai didi

javascript - 如何确保我的scrollView滚动超过KeyboardSpacer的高度?

转载 作者:行者123 更新时间:2023-11-28 05:09:01 25 4
gpt4 key购买 nike

我正在开发一个评论页面,其中包含一个帖子容器(显示帖子本身)和一个在屏幕底部渲染评论的 ListView 。下面是一个带有键盘间隔符的文本输入。当用户输入帖子时,它会上升。一切正常。

整个屏幕被包裹在一个scrollView中。

我基本上想让scrollView在用户点击“发送”后自动向下滚动到屏幕底部以显示用户评论

我在这里发现了这个问题:https://github.com/facebook/react-native/issues/8003这解释了解决方案。

这是我实现后的解决方案:

class Comments extends Component {
contentHeight = 0;
scrollViewHeight = 0;
scrollToBottom(animated = true) {
const scrollHeight = this.contentHeight - this.scrollViewHeight;
if (scrollHeight > 0) {
const scrollResponder = this.refs.scrollView.getScrollResponder();
scrollResponder.scrollResponderScrollTo({ x: 0, scrollHeight, animated });
}
}
render() {
return (
<View style={{ flex: 1 }}>
<ScrollView
ref='scrollView'
onContentSizeChange={(w, h) => this.contentHeight = h}
onLayout={ev => this.scrollViewHeight = ev.nativeEvent.layout.height}
>
<PostSection />
<CommentList />
</ScrollView>
<CommentBar
scrollToBottom={this.scrollToBottom.bind(this)}
/>
<KeyboardSpacer />
</View>
);
}
}

我刚刚将其更改为类扩展组件等

但是,由于某种原因,这种行为实际上以编程方式滚动到顶部,这与它所说的相反。

所以我将第 10 行更改为

scrollResponder.scrollResponderScrollTo({ x: 0, scrollHeight, animated });

scrollResponder.scrollResponderScrollTo({ x: 0, y: scrollHeight, animated });

基本上,我只是添加了 y:scrollHeight 而不是它自己的 scrollHeight

这次它向下滚动,但向下滚动得太远了。

enter image description here

它将在底部添加所有空白。我遗漏了什么明显的东西吗?

我想这一定是因为我使用的键盘垫片,因为空白量看起来是垫片的正确高度。

我该如何解决这个问题?

谢谢!

最佳答案

正如我所看到的,当单击发布按钮时,您的评论会插入到 ListView 的顶部。在新版本的 React Native 中,建议使用“scrollTo(options: {x: number = 0; y: number = 0;animated: boolean = true})”方法以编程方式进行滚动。您应该为 y 值传递 0,然后它会在键盘关闭时滚动到 ScrollView 的顶部。

您正在使用“KeyboardSpacer”,然后您的scrollToBottom方法在更新实际的scrollViewHeight之前首先被调用。同时你的scrollViewHeight是

scrollViewHeight = 初始ScrollViewHeight - keyBoardHeight

然后是公式中scrollHeight的值

constscrollHeight = this.contentHeight - this.scrollViewHeight;

会比预期的要大,这就是为什么 ScrollView 底部出现更多空白的原因。

如果即使在scrollTo方法中将y的值设置为0之后仍然不起作用,那么我建议使用iOS的IQKeyboardManager库。它本身处理所有滚动行为,您无需自己在任何地方编写代码。谢谢!

关于javascript - 如何确保我的scrollView滚动超过KeyboardSpacer的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41529279/

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