滚动到 ScrollView 的顶部

Scroll to top of ScrollView

有没有办法滚动到 ScrollView 的顶部以响应按下按钮?

我可以强制重新render整个页面,但这似乎效率很低。

您可以运行 ScrollView 的"scrollTo" 方法。 Check out the source.

您可以通过设置 ref 属性 并使用 this.refs 来引用 ScrollView 组件,如下所述:https://facebook.github.io/react/docs/more-about-refs.html

  1. 首先向 ScrollView 组件添加一个 ref 属性。示例:<ScrollView ref='_scrollView'>
  2. 然后在您想滚动到顶部的任何地方执行此示例:onPress={() => { this.refs._scrollView.scrollTo(0); }}

一个简单的例子:

<ListView
  ref={ref => this.listView = ref}
  onContentSizeChange={() => {
    this.listView.scrollTo({y: 0})
  }}
/>

用一个按钮控制scrollveiw或listview到顶部是可能的。

首先,您可以使用onScroll方法将事件放入其中来检测ListView或scrollView的event.nativeEvent.contentOffset.y,您可以设置一个状态来控制它s show or hide according to they`。

然后,在你的页面上设置一个按钮,使用onPress方法和.scrollTo方法制作它。

这里有一个实现可以作为参考: https://www.npmjs.com/package/react-native-scrolltotop

希望这对您有所帮助

scrollTo(x, y) 现已弃用。现在最好像这样将对象传递给 scrollTo

this.refs.scrollView.scrollTo({x: 0, y: 0, animated: true})

切中要点。问题是针对 scrollView 的,这对我来说很好用:

<ScrollView
  ref='_scrollView'
  onContentSizeChange={() => { this.refs._scrollView.scrollTo({x: 0, y: 0, animated: true}); }}
 >
< ScrollView  ref={(ref) => { this.scrollListReftop = ref; }}>< /ScrollView>

写这个可以滚动到顶部

this.scrollListReftop.scrollTo({x: 0, y: 0, animated: true})

一个 Hooks 解决方案(在 Typescript 中)

有点复杂,但可能对任何使用函数组件而不是 类 的人有用。

ImperativeScrollView.tsx:

import React, {
  useRef,
  useImperativeHandle,
  forwardRef,
  RefForwardingComponent,
  PropsWithChildren,
} from "react";
import { ScrollView, ScrollViewProps } from "react-native";

export interface ImperativeScrollViewHandles {
  scrollToStart(options?: { animated: boolean }): void;
  scrollToEnd(options?: { animated: boolean }): void;
  scrollTo(options: { x?: number; y?: number; animated?: boolean }): void;
}

const ImperativeScrollView: RefForwardingComponent<
  ImperativeScrollViewHandles,
  PropsWithChildren<ScrollViewProps>
> = (props, ref) => {
  const scrollViewRef = useRef<ScrollView>(null);
  useImperativeHandle(ref, () => ({
    scrollToStart: options => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollTo({
          x: 0,
          y: 0,
          animated: options ? options.animated : true,
        });
      }
    },
    scrollToEnd: options => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollToEnd(options);
      }
    },
    scrollTo: options => {
      if (scrollViewRef.current) {
        scrollViewRef.current.scrollTo(options);
      }
    },
  }));
  return <ScrollView ref={scrollViewRef} {...props} />;
};

export default forwardRef(ImperativeScrollView);


用法:

const MyComponent: React.FC<MyComponentProps> = props => {
  const scrollViewRef = useRef<ImperativeScrollViewHandles>(null);
  return (
    <ImperativeScrollView ref={scrollViewRef}>
      <Button
        title={"Tap me!"}
        onPress={() => {
          if (scrollViewRef.current) {
            scrollViewRef.current.scrollToStart();
          }
        }}
      />
    </ImperativeScrollView>
  );
};

简单示例->

 constructor(props) {
    super(props);
    this.state = {

    }

  this.listView1 = null
  this.listView2 = null
  this.listViewY = 0.0
  this.scrollInterval = null
}

async componentDidMount() {

  this.autoScroll()

}



autoScroll() {
    setTimeout(() => {
      this.scrollInterval = setInterval(() => {
        if (this.listView !== null) {
          this.listView.scrollTo({ y: this.listViewY + 1 })
          this.listViewY += 1
        }
      }, 50);
    }, 1000);
  }

_stopScoller = () => {
if (this.scrollInterval !== null) {
  clearInterval(this.scrollInterval)
}

}

render() {
return(
  <ScrollView style={styles.fullListScrollView} ref={ref => this.listView = ref} onScrollBeginDrag={this._stopScoller}>
 </ScrollView>
)
}

在功能组件中

import { useRef } from 'react';

const scrollRef = useRef();

const onPressTouch = () => {
  scrollRef.current?.scrollTo({
    y: 0,
    animated: true,
  });
}

<ScrollView ref={scrollRef}>
  ...your elements
</ScrollView>

<TouchableOpacity onPress={onPressTouch}></TouchableOpacity>
<TouchableOpacity onPress={()=>this.scrollListReftop.scrollTo({x: 0, y: 200, animated: true})}>
            <Text>scroll up</Text>
          </TouchableOpacity>

 <ScrollView
         ref={(ref) => { this.scrollListReftop = ref; }}
       >

如果您正在使用 FlatList,您可以这样做:

import {  FlatList } from 'react-native';
import React, { useRef } from 'react';

function Test(){
  const flatListRef = useRef(null);

  const onPress = () => {
   flatListRef?.current?.scrollToIndex({ index: 0 });
  }

return (
<>
  <TouchableOpacity onPress={onPress}>
    <Text>Scroll to Top<Text/>
  </TouchableOpacity>
  <FlatList
    ref={flatListRef}
    ...
  />
</>
);
}