【问题标题】:Locking scroll position in FlatList (and ScrollView)在 FlatList(和 ScrollView)中锁定滚动位置
【发布时间】:2017-11-04 02:29:35
【问题描述】:

我正在尝试创建一个 FlatList,它保持当前滚动位置锁定,并且不会因插入列表顶部的新项目而改变。

我创建了一个expo snack 来表明我的意图。

小吃呈现一个带有绿色项目的 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} />;
  }
}

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

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

【问题讨论】:

    标签: react-native scrollview


    【解决方案1】:

    您应该使用 componentDidUpdate() 来实现这一点。

    componentDidUpdate(prevProps, prevState) {
      if(prevProps.data != this.props.data) {
        this.ref.scrollToEnd({ animated: false });
      }
    }
    

    将此添加到您的 MyList 组件中。当组件收到新的 props.data 而不是你当前的 props.data 时,它将调用 scrollToEnd。

    这可能会有所帮助!

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-29
        • 2022-11-17
        • 1970-01-01
        • 1970-01-01
        • 2011-04-26
        相关资源
        最近更新 更多