所以我有一个包含ScrollView
的组件,其中包含许多元素,因此您必须向下滚动很长一段距离。
现在页面底部应该有一个按钮,单击该按钮会将页面滚动回到顶部。
我已经在额外的组件中将按钮创建为FAB(浮动操作按钮)。
它集成在ScrollView
所在的父组件中。
[我发现您必须在ref
组件中创建一个ScrollView
,并在此处实现一个按钮,该按钮使用此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;
如您所见,FloatingButton
方法包含组件onPress()
。
这里是实现:
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
中)中。我想在onPress()
中执行Fab
逻辑,但是如果这样做,则所需的ScrollView
不可用,因为它在父组件中。我的想法是将ref
作为prop
传递到FloatingButton
,但是由于某些原因,这没有用。
有人可以帮我吗?
请查看我的小吃代码。希望对您有帮助。
https://snack.expo.io/@anurodhs2/restless-edamame
[您既可以让父级挂接到FloatingButton
的onPress
函数,也可以将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 });
}