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

问题描述 投票:0回答:3

所以我有一个包含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,但是由于某些原因,这没有用。

有人可以帮我吗?

react-native native-base
3个回答
0
投票

请查看我的小吃代码。希望对您有帮助。

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

0
投票

[您既可以让父级挂接到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>
    );
}

0
投票

您应该确定要滚动到的水平或垂直值,例如此代码段。

onPress={()=> 
   this.scroll.current.scrollTo({ x:0, y:0 });
}
© www.soinside.com 2019 - 2024. All rights reserved.