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

Run*_*ror 2 react-native native-base

所以我有一个ScrollView包含许多元素的组件,所以你必须向下滚动很长一段路。

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

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

它集成在父组件中,该组件ScrollView位于该父组件中。

我发现你必须refScrollView组件中创建一个并在那里实现一个按钮,使用它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;
Run Code Online (Sandbox Code Playgroud)

如您所见,有一个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;
Run Code Online (Sandbox Code Playgroud)

现在的问题是:我应该在哪里做这个onPress()方法?因为如果我将它留在父组件中,它将无法工作,因为它不直接位于Fab(in FloatingButton) 中。我想在 中执行onPress()逻辑Fab,但如果我这样做,ScrollView它需要的不可用,因为它在父组件中。我的想法是,也许传递refprop进入FloatingButton,但由于某些原因,这没有奏效。

有人可以帮帮我吗?

eme*_*nto 8

您可以让父级挂钩到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>
    );
}
Run Code Online (Sandbox Code Playgroud)