我在React Select元素中禁用大型列表中的某些选项时遇到问题。我有大约6,500个选项加载到选择中。起初我遇到了搜索功能滞后的问题但后来我开始使用react-select-fast-filter-options来解决这个问题。现在问题是我需要禁用某些选项,具体取决于propType“选择”。这是代码:
import React, {Component} from 'react'
import PropTypes from 'prop-types';
import 'react-select/dist/react-select.css'
import 'react-virtualized/styles.css'
import 'react-virtualized-select/styles.css'
import Select from 'react-virtualized-select'
import createFilterOptions from 'react-select-fast-filter-options';
let options = [];
if(typeof stockSearchStocks !== 'undefined') {
//loads in all available options from backend by laying down a static js var
options = stockSearchStocks
}
const filterOptions = createFilterOptions({options});
class StockSearch extends Component {
static propTypes = {
exchanges: PropTypes.array.isRequired,
onSelectChange: PropTypes.func.isRequired,
searchDisabled: PropTypes.bool.isRequired,
picks: PropTypes.array.isRequired,
stock_edit_to_show: PropTypes.number
}
/**
* Component Bridge Function
* @param stock_id stocks id in the database
*/
stockSearchChange = (stock_id) => {
this.props.onSelectChange(stock_id);
}
//this is my current attempt to at least
//disable options on component mount but this doesn't seem to be working
componentWillMount = () => {
console.log('picks!: ' + JSON.stringify(this.props.picks));
let pickIDs = this.props.picks.map((p) => p.stock_id);
options = options.map((o) => {
// console.log(pickIDs.indexOf(o.value));
if(pickIDs.indexOf(o.value)) {
// console.log('here is the option: ' + JSON.stringify(o));
// console.log('here is the option: ' + o.disabled);
o.disabled = true;
}
})
}
/**
* handles selected option from the stock select
* @param selectedOption
*/
handleSelect = (selectedOption) => {
this.stockSearchChange(selectedOption.value);
}
render() {
return (
<div className="stock-search-container">
<Select
name="stock-search"
options={options}
placeholder="Type or select a stock here..."
onChange={this.handleSelect}
disabled={this.props.searchDisabled}
value={this.props.stock_edit_to_show}
filterOptions={filterOptions}
/>
</div>
)
}
}
export default StockSearch;
我已经尝试过滤选择道具并更改选项变量以包含disabled:true
但这滞后于应用程序,我不确定现在我是否会使用react-select-fast-filter-options,因为它似乎做某种索引。有没有办法过滤选项var来查找picks prop的所有实例并快速禁用这些选项?
isDisabled = {this.props.disabled}
你正在传递一个错误的道具..对于v2,道具是isDisabled。
在react-select v2中:
1)在您的选项数组中添加一个属性'disabled':'yes'(或任何其他用于标识禁用选项的对)
2)使用反应选择组件的isOptionDisabled props来根据'disabled'属性过滤选项
这是一个例子:
import Select from 'react-select';
const options = [
{label: "one", value: 1, disabled: 'yes'},
{label: "two", value: 2]
render() {
<Select id={'dropdown'}
options={options}
isOptionDisabled={(option) => option.disabled === 'yes'}>
</Select>
}
使用以下命令禁用选项。
import Select from 'react-select';
render() {
const options = [
{label: "a", value: "a", disabled: true},
{label: "b", value: "b"}
];
return (
<Select
name="myselect"
options={options}
</Select>
)
}