【发布时间】:2021-01-04 10:10:01
【问题描述】:
我尝试从 react-select 库中自定义 Select 组件。
我使用span 元素自定义了multiSelectValue,并在标签中添加了逗号。但它不适用于输入。在下拉列表中选择项目时,它按预期工作。但是当我尝试为搜索选项输入值时,输入是焦点,span 项目向左移动,结果字段变为空。
多选
export default function App() {
const [values, setValues] = useState([]);
return (
<div className="root">
<Select
styles={styles}
isSearchable
isMulti
getOptionValue={(option) => option["value"]}
options={options}
value={values}
onChange={(options) => {
setValues(() => options);
}}
components={{
MultiValue: CustomMultiValue
}}
/>
</div>
);
}
自定义选择值
function CustomMultiValue(props) {
const { getValue, data } = props;
const selectedOptions = getValue();
const currentOptionIdx = selectedOptions.findIndex(
(option) => option.value === data.value
);
return (
<span>
{data.label}
{currentOptionIdx === selectedOptions.length - 1 ? "" : ", "}
</span>
);
}
沙盒项目https://codesandbox.io/s/boring-knuth-kfo1e?file=/src/CustomMultiValue.js
【问题讨论】:
标签: javascript reactjs react-select