如何修改React-Select多选组件,使其显示最后选中的选项?
解决方案
要实现显示最后(最新)选中的选项,只需修改自定义ValueContainer组件中获取选中项的逻辑,将原本取第一个选中项的代码改为取最后一个即可:
修改关键代码
在自定义ValueContainer组件里,把获取第一个选中项的逻辑:
const [firstValue] = values;
替换为获取最后一个选中项:
const lastValue = values.length > 0 ? values[values.length - 1] : null;
然后在渲染时使用lastValue替代原来的firstValue即可。
完整修改后的示例代码
import React from "react"; import Select from "react-select"; const options = [ { value: "ocean", label: "Ocean" }, { value: "blue", label: "Blue" }, { value: "purple", label: "Purple" }, { value: "red", label: "Red" }, { value: "orange", label: "Orange" }, { value: "yellow", label: "Yellow" }, { value: "green", label: "Green" }, { value: "forest", label: "Forest" }, { value: "slate", label: "Slate" }, { value: "silver", label: "Silver" } ]; const ValueContainer = ({ children, ...props }) => { const { values, getValue } = props.selectProps; const lastValue = values.length > 0 ? values[values.length - 1] : null; return ( <div className="value-container"> {lastValue && ( <div className="single-value"> {lastValue.label} {values.length > 1 && ( <span className="count">({values.length})</span> )} </div> )} {children.slice(1)} </div> ); }; export default () => ( <Select closeMenuOnSelect={false} components={{ ValueContainer }} isMulti options={options} /> );
说明
- 通过
values.length - 1获取数组最后一个元素,也就是最新选中的选项 - 保留了选中总数的显示逻辑,当选中多个选项时,会在最后选中的选项标签后显示选中数量
- 处理了未选中任何选项的边界情况,避免出现报错
内容的提问来源于stack exchange,提问作者Stephan Du Toit
相关产品推荐
相关产品推荐

