如何在 React Native 中滚动到 View?

Sen*_*ika 1 javascript focus view react-native

我正在使用 React Native 开发一个应用程序。在那里,我想View在按下按钮时滚动到 a 。我试过这样的事情。

render() {
  return(
    <View ref={field => this.myView = field} >
      //something inside the view
    </View>
  )
}
Run Code Online (Sandbox Code Playgroud)

然后,尝试

this.myView.focus()
Run Code Online (Sandbox Code Playgroud)

但是,它不起作用。

我想得到如下 GIF 演示所示的结果。这该怎么做?

在此处输入图片说明

Naz*_*vin 9

您应该存储ScrollViewref 并使用scrollViewRef.scrollTo()

render() {
  return(
    <ScrollView ref={ref => this.scrollViewRef = ref}>
      <View 
        // you can store layout for each of the fields
        onLayout={event => this.layout = event.nativeEvent.layout}
      > 
        // some field goes here
      </View>
    </ScrollView>
  )
}
Run Code Online (Sandbox Code Playgroud)

然后当发生错误时只需滚动到您的字段this.scrollViewRef.scrollTo({ y: this.layout.y, animated: true });

更新: 可以在这个 repo 中找到一个工作示例。

  • 看一下这个 GitHub 存储库,有一个工作示例。https://github.com/nazarlitvin/rn-scroll-sample (3认同)
  • 你可以用`FlatList`和`scrollToIndex`来处理它,在我的演示中也实现了它。 (2认同)