1

我问是因为我看到的例子都在 es6 类中。

并且:我将我的 es6 类重构为一个功能组件。现在不再出现任何行。而且也没有错误。似乎行渲染器不再渲染任何行。

4

1 回答 1

3

是的,您可以使用功能组件react-virtualized

它的性能是否与类组件一样好?我不知道,请在评论中告诉我;)

例子:

import React from 'react'
import {Grid, Typography} from '@material-ui/core'
import PackageItem from './PackageItem'
import {PackagesByCategory} from '../functions/src/types'
import {makeStyles} from '@material-ui/core/styles'
import {WindowScroller, AutoSizer, List, ListRowRenderer, CellMeasurer, CellMeasurerCache} from 'react-virtualized'


const useStyles = makeStyles(theme => ({
    container: {
        minHeight: "80vh",
        width: "100%"
    },
    title: {
        marginTop: 64,
    },
}))

const cache = new CellMeasurerCache({
    defaultHeight: 60,
    fixedWidth: true
});


const PackageCategoriesList = ({packagesByCategories}: PackageCategoriesList) => {
    const classes = useStyles()

    if(!packagesByCategories) {
        return <></>
    }

    const rowRender: ListRowRenderer = ({index, key, style, parent}) => {
        const packageByCategory = packagesByCategories[index]

        return <CellMeasurer
            cache={cache}
            columnIndex={0}
            key={key}
            overscanRowCount={10}
            parent={parent}
            rowIndex={index}
        >
            <Grid item key={key} style={style}>
                    <Typography variant="h1" className={classes.title}>
                        {packageByCategory.category.name}
                    </Typography>
                </Grid>
        </CellMeasurer>
    }

    return <div className={classes.container}>
        <WindowScroller
            scrollElement={window}>
            {({height, isScrolling, registerChild, onChildScroll, scrollTop}) => (
                <div className={classes.list}>
                    {console.log("re der list" , height, isScrolling, scrollTop)}
                    <AutoSizer disableHeight>
                        {({width}) => (
                            <div ref={registerChild}>
                                <List
                                    autoHeight
                                    height={height}
                                    isScrolling={isScrolling}
                                    onScroll={onChildScroll}
                                    overscanRowCount={2}
                                    rowCount={packagesByCategories.length}
                                    rowHeight={cache.rowHeight}
                                    rowRenderer={rowRender}
                                    scrollTop={scrollTop}
                                    width={width}
                                />
                            </div>
                        )}
                    </AutoSizer>
                </div>
            )}
        </WindowScroller>

    </div>
}

export default PackageCategoriesList

于 2020-10-17T17:01:10.367 回答