简体   繁体   中英

How to scroll into View in React Native?

I'm developing an app using React Native. There, I want to scroll into a View when I press a button. I've tried something like this.

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

then, tried

this.myView.focus()

But, it doesn't work.

I want to get the result as shown in the following GIF demo. How to do this?

在此处输入图像描述

You should store ScrollView ref and use 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>
  )
}

And then when an error occurs just scroll to your field this.scrollViewRef.scrollTo({ y: this.layout.y, animated: true }); .

Update: a working example can be found in this repo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM