import React, { Component } from 'react';
import { Alert, AppRegistry, FlatList, Text, TextInput, View } from 'react-native';
export default class PizzaTranslator extends Component {
constructor(props) {
super(props);
this.state = {text: ''};
}
_onload() {
this.abc.scrollTo({x: 0, y: 0, animated: true});
}
render() {
return (
<View>
<FlatList
data={[
{key: 'Devin'},
{key: 'Jackson'},
{key: 'James'},
{key: 'Joel'},
{key: 'John'},
{key: 'Jillian'},
{key: 'Jimmy'},
{key: 'Julie'},
{key: 'Devin'},
{key: 'Jackson'},
{key: 'James'},
{key: 'Joel'},
{key: 'John'},
]}
renderItem={({item}) => <Text>{item.key}</Text>}
onScrollBeginDrag={this._onload}
ref={(FlatList) => {this.abc = FlatList;}}
/>
</View>
);
}
}
// skip this line if using Create React Native App
AppRegistry.registerComponent('AwesomeProject', () => PizzaTranslator);
如何使用 scrollTo 方法?它是如何工作的?
你的例子并不完全清楚。从文档中可以看出,在 react-native- ScrollView和FlatList中有两个组件可以实现具有可滚动内容的容器。第一个同时绘制所有后代(顺便说一下,这对性能有非常负面的影响),而第二个则“懒惰”,只绘制范围内的后代。
关于方法, ScrollView 只有ScrollTo,它将滚动的坐标作为参数之一,而ScrollToEnd,顾名思义,滚动到最后。FlatList 会更丰富,它有四个方法,从名字上不难猜出其用途:scrollToEnd、scrollToIndex、scrollToItem、scrollToOffset。
scrollToIndex使容器按顺序将内容滚动到某个索引。 scrollToItem使容器按值将内容滚动到特定索引。后者更“重”,文档建议使用按索引滚动。
FlatList 和 scrollToEnd、scrollToIndex、scrollToItem 的工作示例:https ://snack.expo.io/H1bFiiJcf