react-select-为下拉菜单和控件显示不同的文本/标签?

Mel*_*ssa 3 reactjs react-select

在我的“反应选择”下拉列表中,标签长数百个字符。在“控制”芯片中,我想显示下拉菜单中的简短版本。这可能吗?

编辑:我要设置芯片的文本,而不是像素宽度。

Lau*_*ura 6

解决方案1

可以将property与multiple值Select一起使用时,自定义控制芯片的样式,styles如下例所示:

const customStyles = {

    multiValue: (base, state) => ({
      ...base,
     // set all chips to a maximum of 100 pixels
      maxWidth: "100px"
    })
  };
Run Code Online (Sandbox Code Playgroud)

这是一个较短的长标签版本的实时示例。我放置了特殊(且难看)的背景,以便您可以看到每个容器的开始和结束位置。

解决方案2

根据评论请求,这是剪切所选选项的替代解决方案。您可以MultiValue使用prop 覆盖组件components。在此组件内,您将可以访问选项标签并应用substring功能以尽可能短地截断标签。

const MultiValue = props => {
// truncate the string to 3 characters
   const content = props.children.substring(0, 3);
   return <components.MultiValue {...props}>{content}...</components.MultiValue>;
};
Run Code Online (Sandbox Code Playgroud)

这是该替代选项的现场示例

解决方案3

与解决方案2相同,如果您事先知道选项标签和要显示的作物,则可以在options数组中设置一个额外的props,如下所示:

const options = [
  {
    label:
      "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi augue sem, bibendum quis mollis amet.",
    // you can name this new prop has you want
    chipLabel: "Lorem ipsum",
    value: "1"
  },
  {
    label:
      "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium.",
    chipLabel: "Sed ut perspiciatis",
    value: "2"
  },
  {
    label:
      "Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?",
    chipLabel: "Ut enim",
    value: "3"
  }
];
Run Code Online (Sandbox Code Playgroud)

然后使用以下代码覆盖该组件:

const MultiValue = props => (
  <components.MultiValue {...props}>
    {props.data.chipLabel}
  </components.MultiValue>
);

<Select options={options} components={{ MultiValue }} />
Run Code Online (Sandbox Code Playgroud)

这里有一个活生生的例子

单值解决方案

如果要显示的值与选择选项中的值不同,SingleValue我建议使用解决方案3并按以下方式更改组件:

const SingleValue = props => (
  <components.SingleValue {...props}>
    {props.data.chipLabel}
  </components.SingleValue>
);

<Select options={options} components={{ SingleValue }} />
Run Code Online (Sandbox Code Playgroud)

这里有一个活生生的例子

  • 如果不使用@JimOtt替换组件,则应如[此示例](https://codesandbox.io/s/5w60l5qmx)所示,否则,我建议您使用代码来调试新问题 (2认同)