首页 > 解决方案 > FlatList React Native中的平滑scrollToOffset

问题描述

我曾尝试将两个Flatlist与状态同步滚动,但我的想法是,由于重新渲染,滚动会抖动、滞后且不平滑。但我尝试引用 React 元素,但没有帮助。结果是一样的,滚动就像是一个人被触电和电击,也就是颤抖

代码如下:

import * as React from 'react';
import { Text, View, StyleSheet, FlatList, Button } from 'react-native';
import Constants from 'expo-constants';

export default function App() {

  const listRefOne = React.useRef();
  const listRefTwo = React.useRef();

  const handleRef = (listRef, offset) => {

    if (listRef === listRefOne) {
      listRefTwo.current.scrollToOffset({ animated: true, offset: offset });
      console.log('One', offset);
    }

    if (listRef === listRefTwo) {
      listRefOne.current.scrollToOffset({ animated: true, offset: offset });
      console.log('Two', offset);
    }

  };

  return (
    <View style={styles.container}>

      <MyListView listRef={listRefOne} handleRef={handleRef} />
      <MyListView listRef={listRefTwo} handleRef={handleRef} />

    </View>
  );
}

const generateData = () => {
  const temp = [];
  for (var i = 1; i <= 100; i++) {
    temp.push({ id: i, title: `# ${i} Hello` });
  }
  return temp;
};

const mydata = generateData();

const MyListView = ({ listRef, handleRef }) => {

  const handleScroll = (offset) => handleRef(listRef, offset);

  return (
    <FlatList
      ref={(list) => {
        listRef.current = list;
      }}
      style={styles.itemView}
      data={mydata}
      renderItem={({ item }) => (
        <Text style={{ fontSize: 20 }}>{item.title}</Text>
      )}
      keyExtractor={(item) => item.id}
      onScroll={(e) => handleScroll(e.nativeEvent.contentOffset.y)}
    />

  );
};

const styles = StyleSheet.create({
  container: {
    flex: 2,
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  itemView: {
    flexGrow: 1,
    backgroundColor: '#efefef',
    margin: 3,
  },
});

世博链接

标签: javascriptreact-nativereact-native-flatlistreact-native-scrollview

解决方案


推荐阅读