如何在react-native中按下onPress按钮?

时间:2018-02-06 13:22:31

标签: button react-native scroll onpress

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

2 个答案:

答案 0 :(得分:11)

我假设您在页面上使用ScrollView,因为只要在底部按下按钮,您就想滚动到顶部。在这种情况下,您可以使用scrollTo({x: 0, y: 0, animated: true}) ScrollView方法。您可以在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组件,它还有一个通过名为scrollToOffset()的ref公开的方法。

答案 1 :(得分:0)

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

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

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

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