React Native滚动视图:在按钮点击时滚动到顶部

4

我有一个包含许多元素的组件,使用了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;

如您所见,这里有一个名为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 中)。我想在Fab中编写onPress()逻辑,但这样做的话,它需要的ScrollView在父组件中不可用。我的想法是将ref作为prop传递到FloatingButton中,但出于某些原因,这种方法没有奏效。请问有人可以帮帮我吗?
3个回答

14

你可以让父组件钩入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>
    );
}

你真是个天才!运行得非常顺畅。 - RuntimeError
经过100多种解决方案,这是唯一一个真正有效的。 - Nicolas Silva
因为自动完成没有显示任何类似于scrollTo的内容,所以我花了很多时间在这上面。第一次尝试就成功了。 - sarfrazanwar
属性 'scrollRef' 不存在。 - Chanrithisak Phok

2
你应该确定你想要滚动到的水平或垂直值,就像这个代码片段一样。
onPress={()=> 
   this.scroll.current.scrollTo({ x:0, y:0 });
}

1
请看一下我的小吃代码。希望它对你有所帮助。
https://snack.expo.io/@anurodhs2/restless-edamame

首先,非常感谢您的帮助。您的代码在我的应用程序中运行良好。然而,到目前为止我一直使用功能组件,并且想继续使用它们。您在示例中使用了类组件。是否也可以在功能组件中实现? - RuntimeError

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接