Sri*_*tam 41
ref向ScrollView组件添加属性.例:<ScrollView ref='_scrollView'>onPress={() => { this.refs._scrollView.scrollTo(0); }}Ima*_*sta 31
在功能组件中
import { useRef } from 'react';
const scrollRef = useRef();
const onPressTouch = () => {
scrollRef.current?.scrollTo({
y: 0,
animated: true,
});
}
<ScrollView ref={scrollRef} >
</ScrollView>
<TouchableOpacity
onPress={onPressTouch}>
</TouchableOpacity>
Run Code Online (Sandbox Code Playgroud)
Jar*_*iuk 29
您可以运行ScrollView的"scrollTo"方法.查看来源.
您可以通过设置ref属性并使用this.refs来引用ScrollView组件,如下所述:https://facebook.github.io/react/docs/more-about-refs.html
sen*_*tor 21
一个简单的例子:
<ListView
ref={ref => this.listView = ref}
onContentSizeChange={() => {
this.listView.scrollTo({y: 0})
}}
/>
Run Code Online (Sandbox Code Playgroud)
Kie*_*per 13
有点复杂,但对于使用函数组件而不是类的任何人来说可能很有用。
命令滚动视图.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);
Run Code Online (Sandbox Code Playgroud)
用法:
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>
);
};
Run Code Online (Sandbox Code Playgroud)
Mju*_*ice 12
scrollTo(x,y)现已弃用.现在最好将一个对象传递给scrollTo,如下所示:
this.refs.scrollView.scrollTo({x: 0, y: 0, animated: true})
小智 9
< ScrollView ref={(ref) => { this.scrollListReftop = ref; }}>< /ScrollView>
Run Code Online (Sandbox Code Playgroud)
写这个让滚动在顶部
this.scrollListReftop.scrollTo({x: 0, y: 0, animated: true})
Run Code Online (Sandbox Code Playgroud)
小智 6
说到点子上了。问题是针对 scrollView 的,这对我来说很好用:
<ScrollView
ref='_scrollView'
onContentSizeChange={() => { this.refs._scrollView.scrollTo({x: 0, y: 0, animated: true}); }}
>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53660 次 |
| 最近记录: |