[英]How to set max number of items that can be selected in react-select?
我正在使用 react-select 中的 CreatableSelect 組件。 現在用戶可以選擇任意數量的項目,但我希望用戶選擇的項目不超過 5 個。 如何限制可以選擇的最大選項數?
<CreatableSelect
classes={classes}
styles={selectStyles}
textFieldProps={{
label: "Tags"
}}
options={suggestions}
components={components}
value={this.state.multi}
onChange={this.handleChange("multi")}
placeholder=""
isMulti
/>
我建議您使用自定義組件Menu
和isValidNewOption
的組合,如以下代碼:
// For this example the limite will be 5
const Menu = props => {
const optionSelectedLength = props.getValue().length || 0;
return (
<components.Menu {...props}>
{optionSelectedLength < 5 ? (
props.children
) : (
<div>Max limit achieved</div>
)}
</components.Menu>
);
};
function App() {
const isValidNewOption = (inputValue, selectValue) =>
inputValue.length > 0 && selectValue.length < 5;
return (
<div className="App">
<Creatable
components={{ Menu }}
isMulti
isValidNewOption={isValidNewOption}
options={options}
/>
</div>
);
}
這里有一個活生生的例子。
這個想法是為了防止用戶訪問限制 X 之后的選項(示例中為 5),並防止通過isValidNewOption
創建時enter
鍵盤事件。
<CreatableSelect
classes={classes}
styles={selectStyles}
options={this.state.multi.length > 4 ? this.state.multi : suggestions}
components={Components}
value={this.state.multi}
placeholder="Tags"
onChange={(values) => this.setState({ multi: values })}
isValidNewOption={isValidNewOption} //Look at Marked Answer
isMulti
/>
可以在此處找到有關如何解決此問題的主要文檔:
https://github.com/JedWatson/react-select/issues/1341
const MultiCreatable = ({ options, handleChange, handleCreate, value, maxOptions }) => {
return (
<CreatableSelect
isMulti
placeholder={placeholder}
onChange={handleChange}
options={value.length === maxOptions ? [] : options}
noOptionsMessage={() => {
return value.length === maxOptions ? 'You have reached the max options value' : 'No options available' ;
}}
onCreateOption={handleCreate}
value={value}
/>
)
}
對於我的情況,我使用了 react-select 中的普通Select Component。
<Select
options={industries}
value={industry}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={(e) => this.handleSelectChange(e, "industry")}
isMulti
/>
和 handleSelectChange-
handleSelectChange = (e, name) => {
console.log(e)
if(e.length < 6){
return this.setState({
[name]: e
})
}
}
並聲明 -
this.state = { industry: [] }
我正在分享我的完整工作組件,我認為它可以提供幫助>>
import React, { useState } from 'react';
import Select from 'react-select';
import makeAnimated from 'react-select/animated';
const animatedComponents = makeAnimated();
const ReactSelect = ({ data }) => {
const maxOptions = 5;
const [selectedOption, setSelectedOption] = useState([]);
const handleTypeSelect = e => {
setSelectedOption(e);
};
return (
<Select
onChange={handleTypeSelect}
getOptionLabel={x => x.name}
getOptionValue={x => x.slug}
components={animatedComponents}
isMulti
options={selectedOption.length === maxOptions ? [] : data}
noOptionsMessage={() => {
return selectedOption.length === maxOptions
? 'You have reached the max options value'
: 'No options available';
}}
label='tags'
/>
);
};
export default ReactSelect;
一個非常簡單的方法是:
<Select
value={tags}
onChange={(v) => v.length < 4 ? setTags(v): null}
isMulti
name='tags'
options={options}
className='basic-multi-select'
classNamePrefix='select'
/>
只需添加一個簡單的三元檢查你想要多少項目
我找到了更簡單和干凈的方法,不需要額外的操作。 這種方式基於禁用“反應選擇”的輸入組件。 仔細看看參數inputProps
。
它看起來像:
import Select from 'react-select';
import useField from 'client/components/hooks/useField';
const MultiSelect = ({
async,
creatable,
maxItems,
...restProps,
}) => {
const selectProps = {
...restProps,
// "inputProps: {disabled: boolean}" - our goal
...(typeof maxItems === 'number' && maxItems === restProps.value?.length ? {inputProps: {disabled: true}} : {})
};
const creatableTag = async ? Select.CreatableAsync : Select.Creatable;
const SelectTag = creatable ? creatableTag : selectTag;
return (
<div>
<SelectTag {...selectProps} />
</div>
);
};
const SomeComponentWithMultiSelect = () => {
const field = useField('data.name'); // field contains: {value: string[], ...}
const items = [
{
label: 'firstValue',
value: 1,
},
{
label: 'secondValue',
value: 2,
},
];
return (
<MultiSelect
items={items}
{...field}
creatable
maxItems={1} // {1} as our limit
/>
)
};
export default SomeComponentWithMultiSelect;
所以你不需要管理多余的組件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.