在FlatList(和ScrollView)中锁定滚动位置

Guy*_*gal 12 scrollview react-native

我正在尝试创建一个FlatList,使当前滚动位置保持锁定状态,并且不会被插入列表顶部的新项目更改.

我创造了一个世博小吃来展示我的意图.

小吃呈现带有绿色物品的ScrollView,最后是黑色物品.当应用程序启动时,它会滚动到列表的底部.五秒钟后,在顶部插入10个项目,并且滚动位置根据这些项目的总大小而变化.

这是世博小吃的代码:

import React, { Component } from 'react';
import { View, FlatList } from 'react-native';

const renderItem = ({ item }) => {
  let backgroundColor;
  if (item == 10) {
    backgroundColor = "black"
  }
  else {
    backgroundColor = item % 2 == 0 ? 'green' : 'blue'
  }

  return (
    <View
      style={{
        width: 200,
        height: 50,
        backgroundColor,
        margin: 10,
      }}
    />
  );
};

const MyList = class extends Component {
  componentDidMount() {
    setTimeout(() => this.ref.scrollToEnd({ animated: false }), 500);
  }
  render() {
    return (
      <FlatList
        ref={r => this.ref = r}
        data={this.props.data}
        renderItem={this.props.renderItem}
      />
    );
  }
};

export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      items: [2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 10],
    };
  }

  componentDidMount() {
    const items = [...this.state.items];
    items.unshift(1, 1, 1, 1, 1, 1, 1, 1, 1, 1);
    setTimeout(() => this.setState({ items }), 5000);
  }

  render() {
    return <MyList renderItem={renderItem} data={this.state.items} />;
  }
}
Run Code Online (Sandbox Code Playgroud)

我想保持滚动位置锁定,这意味着 - 当插入项目时,滚动位置不会改变(或者至少在某种程度上用户不知道发生了什么)

有没有办法用FlatList和ScrollView的当前API做到这一点?要实现此功能需要实现什么?

小智 -1

你尝试过使用keyExtractor吗?(https://facebook.github.io/react-native/releases/next/docs/flatlist.html#keyextractor)。

它可能有助于反应避免重新渲染,因此请尝试为每个项目使用唯一的键。