【问题标题】:How can i scroll top on onPress of button in react-native?如何在 react-native 中的 onPress 按钮上滚动顶部?
【发布时间】:2018-07-16 13:56:04
【问题描述】:

我在简单屏幕的底部添加了按钮,我想在按下按钮时滚动顶部。什么代码添加到按钮onPress?,请提出任何解决方案,提前谢谢。

【问题讨论】:

    标签: button react-native scroll onpress


    【解决方案1】:

    我假设您在页面上使用 ScrollView,因为您想在底部按下按钮时滚动到顶部。在这种情况下,您可以使用ScrollViewscrollTo({x: 0, y: 0, animated: true}) 方法。你可以像这样在 render 方法之前调用一个函数:

    goToTop = () => {
       this.scroll.scrollTo({x: 0, y: 0, animated: true});
    }
    render() {
     return (
      <ScrollView
        ref={(c) => {this.scroll = c}}
      >
        // [rest of your code here...]
        <Button title='Go To Top' onPress={this.goToTop} />
      </ScrollView>
     )
    }
    

    基本上,您必须为您的 scrollView 创建一个引用 (ref),然后您可以在代码中的任何位置调用它的方法。

    如果您不使用 ScrollView,而是使用 Flatlist 组件,它还有一个通过其 refs 公开的方法,称为 scrollToOffset()。

    【讨论】:

    • 如何滚动底部?
    【解决方案2】:

    在 React Native 中对于功能组件,需要做以下事情才能在 ScrollView 中滚动 Top-

    1.在功能组件中全局定义:- const scroll = React.createRef();

    1. 然后,在 ScrollView 中添加:- ref={scroll}。

    3.最后,点击添加:- scroll.current.scrollTo(0); // 将滚动到 y 位置 0 的顶部

    【讨论】:

      【解决方案3】:

      // const scroll = React.createRef();

      如果你得到 error that scroll.current is Null 然后试试这个

      const scroll = React.useRef();

      这在我的案例中有效。

      【讨论】:

        猜你喜欢
        • 2018-07-29
        • 2020-10-27
        • 1970-01-01
        • 2017-06-29
        • 2019-02-18
        • 1970-01-01
        • 1970-01-01
        • 2020-03-30
        • 1970-01-01
        相关资源
        最近更新 更多