如何设置可以在 react-select 中 selected 的最大项目数?
How to set max number of items that can be selected in react-select?
我正在使用来自 react-select 的 CreatableSelect 组件。现在用户可以 select 任意数量的项目,但我希望用户 select 不超过 5 个项目。如何限制可以 selected 的最大选项数?
<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>
);
}
这里是live example.
这个想法是为了防止用户访问限制 X 之后的选项(示例中为 5),并防止通过 isValidNewOption
prop.[=16] 创建时的 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
/>
对于我的情况,我使用了来自 react-select.
的正常 Select 组件
<Select
options={industries}
value={industry}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={(e) => this.handleSelectChange(e, "industry")}
isMulti
/>
并处理Select变化-
handleSelectChange = (e, name) => {
console.log(e)
if(e.length < 6){
return this.setState({
[name]: e
})
}
}
和状态 -
this.state = { industry: [] }
可在此处找到有关如何解决此问题的主要文档:
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}
/>
)
}
我正在分享我的完整工作组件,我认为它可以提供帮助>>
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'
/>
只需添加一个简单的三元检查来确定您想要的项目数量
我找到了更简单干净的方法,没有额外的操作。
这种方式基于禁用 'react-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;
因此您无需管理多余的组件。
我正在使用来自 react-select 的 CreatableSelect 组件。现在用户可以 select 任意数量的项目,但我希望用户 select 不超过 5 个项目。如何限制可以 selected 的最大选项数?
<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>
);
}
这里是live example.
这个想法是为了防止用户访问限制 X 之后的选项(示例中为 5),并防止通过 isValidNewOption
prop.[=16] 创建时的 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
/>
对于我的情况,我使用了来自 react-select.
的正常 Select 组件<Select
options={industries}
value={industry}
getOptionLabel={ x => x.id}
getOptionValue={ x => x.industry}
onChange={(e) => this.handleSelectChange(e, "industry")}
isMulti
/>
并处理Select变化-
handleSelectChange = (e, name) => {
console.log(e)
if(e.length < 6){
return this.setState({
[name]: e
})
}
}
和状态 -
this.state = { industry: [] }
可在此处找到有关如何解决此问题的主要文档:
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}
/>
)
}
我正在分享我的完整工作组件,我认为它可以提供帮助>>
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'
/>
只需添加一个简单的三元检查来确定您想要的项目数量
我找到了更简单干净的方法,没有额外的操作。
这种方式基于禁用 'react-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;
因此您无需管理多余的组件。