针对大数据量的渲染优化库:react-virtual的基本使用
针对大数据量的渲染优化库:react-virtual(List)的基本使用
react-virtual库的安装及引用
安装
github地址:https://github.com/bvaughn/react-virtualized
使用命令:
npm install react-virtualized --save
安装过程可能会出现(react版本库以及react-virtualized库之间的存在版本冲突问题)
npm ERR! peer react@"^15.3.0 || ^16.0.0-alpha" from react-virtualized@9.22.3
则使用:
npm install react-virtualized --legacy-peer-deps
使用
// react-virtualized长列表优化
import 'react-virtualized/styles.css';
// List可用于渲染列表内需要重复渲染的节点,
import List from 'react-virtualized/dist/commonjs/List';
// AutoSizer库可以以用于自动获取子List所在父级的宽高,以回调参数的方式传递给List
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
export default class index extends Component {
constructor(props: any) {
super(props);
this.state = {
// 生成长度为1000的随机数组
list: new Array(1000).fill(Math.rendom(0, 1)* 100.toFixed(0))
}
this.rowRenderer = this.rowRenderer.bind(this);
}
// rowRenderer返回需要重复进行渲染的节点
rowRenderer(arg: { key: Key, index: number, isScrolling: unknown, isVisible: any, style: any }) { // 此处为ts写法,js可直接使用对象解构,在函数内使用
return (
<div key={arg.key} style={arg.style}> // stlye一定要用上
{arg.index}
{this.state.list[index]}
</div>
)
}
render() {
return (
<AutoSizer>
{({ width, height }) => ( // 此处width,height为AutoSizer自动获取的父级高度,List可采用也可自定义给定List的高度
<List
width={width} // 定义列表宽度
height={30 * this.props.datalist.length} // 定义列表总高度
rowHeight={30} // 定义每个item的高度
rowCount={this.props.datalist.length} // 需要渲染的列表条数,同时也相当于规定了会渲染的数据条数
rowRenderer={this.rowRenderer} // 需要重复渲染的节点
/>
)}
</AutoSizer>
)
}
}
其他用法及细节参考:使用文档