当行是可变高度时,使用FlatList滚动问题

Gil*_*vik 11 react-native react-native-flatlist

我正在使用FlatList每行可以具有不同高度的位置(并且可以包含来自远程服务器的文本和零个或多个图像的混合).

我无法使用,getItemLayout因为我不知道每行的高度(也不是前面的那些)能够计算出来.

我面临的问题是我无法滚动到列表的末尾(当我尝试时它跳回几行)并且我在尝试使用时遇到问题scrollToIndex(我猜是因为我错过了这个事实getItemLayout).

我写了一个示例项目来演示这个问题:

import React, { Component } from 'react';
import { AppRegistry, StyleSheet, Text, View, Image, FlatList } from 'react-native';
import autobind from 'autobind-decorator';

const items = count => [...Array(count)].map((v, i) => ({
    key: i,
    index: i,
    image: 'https://dummyimage.com/600x' + (((i % 4) + 1) * 50) + '/000/fff',
}));

class RemoteImage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            style: { flex: 1, height: 0 },
        };
    }

    componentDidMount() {
        Image.getSize(this.props.src, (width, height) => {
            this.image = { width, height };
            this.onLayout();
        });
    }

    @autobind
    onLayout(event) {
        if (event) {
            this.layout = {
                width: event.nativeEvent.layout.width,
                height: event.nativeEvent.layout.height,
            };
        }
        if (!this.layout || !this.image || !this.image.width)
            return;
        this.setState({
            style: {
                flex: 1,
                height: Math.min(this.image.height,
                    Math.floor(this.layout.width * this.image.height / this.image.width)),
            },
        });
    }
    render() {
        return (
            <Image
                onLayout={this.onLayout}
                source={{ uri: this.props.src }}
                style={this.state.style}
                resizeMode='contain'
            />
        );
    }
}

class Row extends Component {
    @autobind
    onLayout({ nativeEvent }) {
        let { index, item, onItemLayout } = this.props;
        let height = Math.max(nativeEvent.layout.height, item.height || 0);
        if (height != item.height)
            onItemLayout(index, { height });
    }

    render() {
        let { index, image } = this.props.item;
        return (
            <View style={[styles.row, this.props.style]}>
                <Text>Header {index}</Text>
                <RemoteImage src = { image } />
                <Text>Footer {index}</Text>
            </View>
        );
    }
}

export default class FlatListTest extends Component {
    constructor(props) {
        super(props);
        this.state = { items: items(50) };
    }

    @autobind
    renderItem({ item, index }) {
        return <Row
        item={item}
        style={index&1 && styles.row_alternate || null}
        onItemLayout={this.onItemLayout}
        />;
    }

    @autobind
    onItemLayout(index, props) {
        let items = [...this.state.items];
        let item = { ...items[index], ...props };
        items[index] = { ...item, key: [item.height, item.index].join('_') };
        this.setState({ items });
    }

    render() {
        return (
            <FlatList
                    ref={ref => this.list = ref}
                    data={this.state.items}
                    renderItem={this.renderItem}
                />
        );
    }
}

const styles = StyleSheet.create({
    row: {
        padding: 5,
    },
    row_alternate: {
        backgroundColor: '#bbbbbb',
    },
});

AppRegistry.registerComponent('FlatListTest', () => FlatListTest);
Run Code Online (Sandbox Code Playgroud)

小智 6

使用scrollToOffset()代替:

    export default class List extends React.PureComponent {

        // Gets the total height of the elements that come before
        // element with passed index
        getOffsetByIndex(index) {
            let offset = 0;
            for (let i = 0; i < index; i += 1) {
                const elementLayout = this._layouts[i];
                if (elementLayout && elementLayout.height) {
                    offset += this._layouts[i].height;
                }
            }
            return offset;
        }

        // Gets the comment object and if it is a comment
        // is in the list, then scrolls to it
        scrollToComment(comment) {
            const { list } = this.props;
            const commentIndex = list.findIndex(({ id }) => id === comment.id);
            if (commentIndex !== -1) {
                const offset = this.getOffsetByIndex(commentIndex);
                this._flatList.current.scrollToOffset({ offset, animated: true });
            }
        }

        // Fill the list of objects with element sizes
        addToLayoutsMap(layout, index) {
            this._layouts[index] = layout;
        }

        render() {
            const { list } = this.props;

            return (
                <FlatList
                    data={list}
                    keyExtractor={item => item.id}
                    renderItem={({ item, index }) => {
                        return (
                            <View
                                onLayout={({ nativeEvent: { layout } }) => {
                                    this.addToLayoutsMap(layout, index);
                                }}
                            >
                                <Comment id={item.id} />
                            </View>
                        );
                    }}
                    ref={this._flatList}
                />
            );
        }
    }
Run Code Online (Sandbox Code Playgroud)
  1. 渲染时,我获取列表中每个元素的大小并将其写入数组:

onLayout={({ nativeEvent: { layout } }) => this._layouts[index] = layout}

  1. 当需要将屏幕滚动到元素时,我总结了它前面所有元素的高度并获取滚动屏幕的量(getOffsetByIndex 方法)。

  2. 我使用 scrollToOffset 方法:

this._flatList.current.scrollToOffset({ offset, animated: true });

(this._flatList 是 Fl​​atList 的引用)

  • 如果您想要到达的项目及其之前的项目已经布置好,那么这种方法就有效。但事实并非如此,您提出什么解决方案? (2认同)

rag*_*fin 0

你有没有尝试过scrollToEnd

http://facebook.github.io/react-native/docs/flatlist.html#scrolltoend

正如文档所述,如果没有它,它可能会很卡顿,getItemLayout但对我来说,没有它它确实可以工作