首页 > 解决方案 > 向下滚动到 React Native ScrollView 中的特定视图

问题描述

我希望能够在按下按钮后滚动一个,以便它在屏幕上可见。我怎样才能告诉一个 react-native ScrollView 移动到某个位置?

标签: reactjsreact-nativescrollview

解决方案


您好,您可以使用属性 scrollTo 如下所示

import {useRef} from "react"
import {
  ScrollView,
  Button,
} from 'react-native';

const YouComp = () => {
  const refScrollView = useRef(null);
  const moveTo = () => {
    refScrollView.current.scrollTo({x: value1, y: value2});
    // or just refScrollView.current.scrollTo({x: value1}); if you want to scroll horizontally
    // or just refScrollView.current.scrollTo({y: value2}); if you want to scroll vertically
  }

  return (<>
  <Button onPress={moveTo} title="title" />
  <ScrollView ref={refScrollView}>
    ...
  </ScrollView>
  </>);
}

您可以设置 x 或 y 值或两者

在此处查看完整文档


推荐阅读