Zer*_*rty 6 reactjs react-select react-window
在可搜索的反应选择下拉列表中呈现大量数据的最佳方法是什么?我研究过窗口化,其中仅为在视口中可见的项目创建 DOM 节点。这可以通过使用react-window包和react-select来完成。但是,我想知道是否有比这更好的方法。
这是使用react-window和react-select的窗口实现
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Select from "react-select";
import { FixedSizeList as List } from "react-window";
import "./styles.css";
const options = [];
for (let i = 0; i < 10000; i = i + 1) {
options.push({ value: i, label: `Option ${i}` });
}
const height = 35;
class MenuList extends Component {
render() {
const { options, children, maxHeight, getValue } = this.props;
const [value] = getValue();
const initialOffset = options.indexOf(value) * height;
return (
<List
height={maxHeight}
itemCount={children.length}
itemSize={height}
initialScrollOffset={initialOffset}
>
{({ index, style }) => <div style={style}>{children[index]}</div>}
</List>
);
}
}
const App = () => <Select components={{ MenuList }} options={options} />;
ReactDOM.render(<App />, document.getElementById("root"));
Run Code Online (Sandbox Code Playgroud)
小智 8
我将您提到的解决方案(react-window)与filterOption解决方案以及较少讨论的react-async组件结合起来。这对我来说效果很好。
React-window 会执行某种“延迟加载”,而异步 React 在显示搜索查询之前会显示加载标志。这些加在一起让人感觉更加自然(我有 7000 多个选项)。
这是我第一次回复帖子,所以如果(任何人)有疑问请告诉我,我会尽力回答
import React, { Component } from "react";
import AsyncSelect from "react-select/async";
import { FixedSizeList as List } from "react-window";
import { createFilter } from "react-select";
import "./styles.css";
const TestSelect = (vendorOptions) => {
const options = [];
for (let i = 0; i < vendorOptions["vendorOptions"].length; i = i + 1) {
options.push({ value: vendorOptions["vendorOptions"][i], label: `${vendorOptions["vendorOptions"][i]}` });
}
const loadOptions = (inputValue, callback) => {
setTimeout(() => {
callback(options);
}, 1000);
};
const height = 35;
class MenuList extends Component {
render() {
const { options, children, maxHeight, getValue } = this.props;
const [value] = getValue();
const initialOffset = options.indexOf(value) * height;
return (
<List
height={maxHeight}
itemCount={children.length}
itemSize={height}
initialScrollOffset={initialOffset}
>
{({ index, style }) => <div style={style}>{children[index]}</div>}
</List>
);
}
}
const TestSelectComponent = () => {
return(
<div className ="testDropdown">
<AsyncSelect components={{ MenuList }} cacheOptions defaultOptions loadOptions={loadOptions} filterOption={createFilter({ ignoreAccents: false })}/>
</div>
)
}
return (
<TestSelectComponent />
)
}
export default TestSelectRun Code Online (Sandbox Code Playgroud)
小智 5
如果您查看,您会发现默认值是ignoreAccents: true。这个默认值使得react-select调用一个被调用两次的昂贵函数stripDiacritics。这会导致性能问题。
包括ignoreAccents: false在反应选择中。
例子:filterOption={createFilter({ ignoreAccents: false })}
| 归档时间: |
|
| 查看次数: |
11548 次 |
| 最近记录: |