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

时间:2017-01-08 03:45:28

标签: javascript reactjs react-native

我正在撰写评论页面,其中包含一个帖子容器(显示帖子本身)和一个listView,在屏幕底部呈现评论。下面是带有键盘空间的textInput。当用户输入帖子时,它会突然爆发。一切正常。

整个屏幕都包含在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>
    );
  }
}

我刚把它改成了类扩展组件等

然而,出于某种原因,这种行为实际上以编程方式滚动到TOP,这与它所说的相反。

所以我改变了第10行

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

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

基本上,我只是添加了y: scrollHeight而不是scrollHeight

这次它向下滚动但向下滚动到远处。

enter image description here

它会在底部添加所有空白区域。有什么明显的东西让我失踪吗?

我认为这一定是因为我使用的键盘垫片,因为白色空间的数量看起来与垫片的高度相同。

我该如何解决这个问题?

谢谢!

1 个答案:

答案 0 :(得分:0)

正如我所看到的,单击发布按钮时,您的注释将插入ListView的顶部。在新版本的本地反应中,方法&#39; scrollTo(选项:{x:number = 0; y:number = 0; animated:boolean = true})&#39;建议用于以编程方式滚动。您应该为y值传递0,然后它将滚动到键盘关闭时scrollView的顶部。

您正在使用&#39; KeyboardSpacer&#39;然后你的scrollToBottom方法在更新实际的scrollViewHeight之前一直在调用。同时你的scrollViewHeight是

scrollViewHeight = initialScrollViewHeight - keyBoardHeight

然后是公式

中scrollHeight的值

const scrollHeight = this.contentHeight - this.scrollViewHeight;

会比预期的更大,这就是为什么在scrollView底部会出现更多的空白区域。

如果在scrollTo方法中将y的值加0后仍然无法工作,那么我建议使用IQKeyboardManager库用于iOS。它处理所有滚动行为本身,你自己不编码任何地方。谢谢!