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

How to customize only one option from 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 以获得默认行为。

这里是live example