如何从react-select中只自定义一个选项



我正在使用react select,我只想自定义下拉列表中的一个选项。有这样的机会吗?我想做一些类似的事情:

const CustomOption = ({ innerRef, innerProps, data }) => data.custom
? (<div ref={innerRef} {...innerProps} >I'm a custom link</div>)
: defaultOne //<--- here I would like to keep default option
<ReactSelect
components={{ Option: CustomOption }}
options={[
{ value: 'chocolate', label: 'Chocolate' },
{ value: 'strawberry', label: 'Strawberry' },
{ value: 'vanilla', label: 'Vanilla' },
{ custom: true },
]}
/>

有什么想法吗?

你的感觉很好,你可以通过以下方式实现你的目标:

const CustomOption = props => {
const { data, innerRef, innerProps } = props;
return data.custom ? (
<div ref={innerRef} {...innerProps}>
I'm a custom link
</div>
) : (
<components.Option {...props} />
);
};
const options = [
{ value: "chocolate", label: "Chocolate" },
{ value: "strawberry", label: "Strawberry" },
{ value: "vanilla", label: "Vanilla" },
{ custom: true }
];
function App() {
return <Select components={{ Option: CustomOption }} options={options} />;
}

需要注意的重要事项是将整个props属性传递给components.Option以具有默认行为。

这是一个活生生的例子。

相关内容

最新更新