在React-Select中显示多个值的倒序。

huangapple go评论67阅读模式
英文:

Display reverse order of multi-values in React-Select

问题

I am using React-Select库允许用户从下拉列表中选择多个选项。输入字段的空间有限,因此我已修改代码,仅显示一个选定的选项和显示总选定计数的另一个标签。但是,我要显示的一个选定的选项应该是最后一个选定的选项,而不是第一个。

例如,在下面的屏幕截图中,我首先选择了"Ocean",然后选择了"Orange"(即"Orange"是最近选择的选项)。
我因此希望在输入字段(我相信它被称为ValueContainer)中显示最近选择的选项"Orange"。

我该如何实现这一点?

以下是我目前实施的最小工作示例:

https://codesandbox.io/s/react-select-multivalue-order-64tylo?file=/example.js

英文:

I am using React-Select library to allow users to select multiple options from a dropdown list. The input field is limited in space and therefor I have modified the code to show only one selected option and the another label that shows a count of the total selected.
However, the one selected option that I want to display should be the last selected option, not the first.

For example, in the screenshot below, I have selected "Ocean" first and "Orange" last (ie: "Orange" is the most recent selected option). 在React-Select中显示多个值的倒序。
I therefor want to display the most recent selected option, "Orange", in the input (I believe it is called ValueContainer) field.

How can I go about achieving this?

Below is a minimum working example of what i currently have implemented:

https://codesandbox.io/s/react-select-multivalue-order-64tylo?file=/example.js

答案1

得分: 2

Here is the translated code portion:

const MultiValue = ({ index, getValue, ...props }) => {
  const maxToShow = 1;
  const overflow = getValue()
    .slice(0, -maxToShow)
    .map((x) => x.label);

  return index === getValue().length - maxToShow ? ( // 这里是显示最后一个值而不是第一个的地方
    <components.MultiValue {...props} />
  ) : index === maxToShow ? (
    <MoreSelectedBadge items={overflow} />
  ) : null;
};

在 codesandbox 中的工作示例

英文:

Try this

const MultiValue = ({ index, getValue, ...props }) =&gt; {
  const maxToShow = 1;
  const overflow = getValue()
    .slice(0, -maxToShow)
    .map((x) =&gt; x.label);

  return index === getValue().length-maxToShow ? ( //This is where you show the last value instead of the first
    &lt;components.MultiValue {...props} /&gt;
  ) : index === maxToShow ? (
    &lt;MoreSelectedBadge items={overflow} /&gt;
  ) : null;
};

Working example in codesandbox

huangapple
  • 本文由 发表于 2023年5月25日 21:32:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76332881.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定