React Native Scrollview:点击按钮滚动到顶部



所以我有一个带有ScrollView的组件,它包含许多元素,所以您必须向下滚动很长一段时间。

现在页面底部应该有一个按钮,点击后会将页面滚动回顶部。

我已经在一个额外的组件中创建了一个FAB(浮动动作按钮(按钮。

它集成在ScrollView所在的父组件中。

我发现,您必须在ScrollView组件中创建一个ref,并在那里实现一个按钮,该按钮使用这个ref来进行滚动。简化了,以下是我迄今为止所拥有的:

imports ...
const ParentComponent: React.FC<Props> = () => {
const scroll = React.createRef();
return (
<View>
<ScrollView ref={scroll}>
<SearchResult></SearchResult> // creates a very long list 
<FloatingButton
onPress={() => scroll.current.scrollTo(0)}></FloatingButton>
</ScrollView>
</View>
);
};
export default ParentComponent;

正如您所看到的,存在具有onPress()方法的组件FloatingButton

以下是实现:

import React, {useState} from 'react';
import {Container, Content, Button, Icon, Fab} from 'native-base';
const FloatingButton: React.FC<Props> = () => {
return (
<Fab
position="bottomRight"
onPress={(???}>
<Icon name="arrow-round-up" />
</Fab>
);
};
export default FloatingButton;

现在的问题是:我应该在哪里使用onPress()方法?因为如果我把它留在父组件中,它就不会工作,因为它不直接位于Fab(在FloatingButton中(。我想在Fab中执行onPress()逻辑,但如果这样做,它所需的ScrollView将不可用,因为它在父组件中。我的想法是可能将ref作为prop传递到FloatingButton,但由于某种原因,这不起作用。

有人能帮帮我吗?

您可以让父级挂接到FloatingButtononPress函数中,也可以直接将ref传递给FloatingButton

export const Parent : FC<ParentProps> = props => {
const scrollRef = useRef<ScrollView>();
const onFabPress = () => {
scrollRef.current?.scrollTo({
y : 0,
animated : true
});
}
return (
<View>
<ScrollView ref={scrollRef}>
{/* Your content here */}
</ScrollView>
<FloatingButton onPress={onFabPress} />
</View>  
);
}
export const FloatingButton : FC<FloatingButtonProps> = props => {
const { onPress } = props;
const onFabPress = () => {
// Do whatever logic you need to
// ...
onPress();
}
return (
<Fab position="bottomRight" onPress={onFabPress}>
<Icon name="arrow-round-up" />
</Fab>
);
}

您应该确定要滚动到的水平或垂直值,就像下面的代码片段一样。

onPress={()=> 
this.scroll.current.scrollTo({ x:0, y:0 });
}

请查看我的零食代码。希望对你有帮助。

https://snack.expo.io/@anurodhs2/restless-edamame

最新更新