在 react-select 中更改 selected 值组件

Change selected value component in react-select

有什么方法可以更改 selected 值组件设计,在我的选项菜单中,我显示 CscId 和 CscDesc 但是当我 select 该选项时,我只想显示 CscId .有什么方法可以更改 selected 值组件吗?我 google 这个已经用了 1 天了。请帮助我。

这是我的反应-select

import React  from "react";
import Select from 'react-select';

const costcenterselect = ({ value, onChange, id, datasource }) => {    
  const formatOptionLabel = ({ CscID, CscDesc }) => (            
    <div style={{ display: "flex"}}>
      <div style={{width:'40%'}}>{CscID}</div>                
      <div>{CscDesc}</div>                
    </div>
  );  

  return (
    <div>
      <Select 
        id={id}
        menuIsOpen={true}    
        formatOptionLabel={formatOptionLabel}
        getOptionValue={option => `${option.CscID}`}
        options={datasource}
        onChange={onChange}
        defaultValue={value}        
      />
    </div>           
  )
}

export default costcenterselect;

您可以使用 formatOptionLabel 本身来完成。它有第二个参数,它为您提供 context 之类的元信息,您可以使用它来有条件地呈现。这里有一个working demo.

您可以看到 context === value 允许您呈现所选值,而 context === menu 呈现选项。

const formatOptionLabel = ({ CscID, CscDesc }, { context }) => {
    if (context === "value") {
      return <div>{CscID}</div>;
    } else if (context === "menu") {
      return (
        <div style={{ display: "flex" }}>
          <div style={{ width: "40%" }}>{CscID}</div>
          <div>{CscDesc}</div>
        </div>
      );
    }
  };