【发布时间】:2018-07-16 13:56:04
【问题描述】:
我在简单屏幕的底部添加了按钮,我想在按下按钮时滚动顶部。什么代码添加到按钮onPress?,请提出任何解决方案,提前谢谢。
【问题讨论】:
标签: button react-native scroll onpress
我在简单屏幕的底部添加了按钮,我想在按下按钮时滚动顶部。什么代码添加到按钮onPress?,请提出任何解决方案,提前谢谢。
【问题讨论】:
标签: button react-native scroll onpress
我假设您在页面上使用 ScrollView,因为您想在底部按下按钮时滚动到顶部。在这种情况下,您可以使用ScrollView 的scrollTo({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()。
【讨论】:
在 React Native 中对于功能组件,需要做以下事情才能在 ScrollView 中滚动 Top-
1.在功能组件中全局定义:- const scroll = React.createRef();
3.最后,点击添加:- scroll.current.scrollTo(0); // 将滚动到 y 位置 0 的顶部
【讨论】:
// const scroll = React.createRef();
如果你得到 error that scroll.current is Null 然后试试这个
const scroll = React.useRef();
这在我的案例中有效。
【讨论】: