简体   繁体   English

react-select使用标签作为传递给组件的值,而不是选项数组中的值

[英]react-select use label as value passed to component instead of value from options array

I am coming across a common problem when using react-select . 使用react-select时遇到一个常见问题。 All works well if you don't have to pass a value to the component, but in cases where you do it is quite inconvenient. 如果您不必将value传递给组件,那么所有方法都可以很好地工作,但是在您这样做的情况下,这样做非常不便。

Often the value and the label will differ. 通常, valuelabel会有所不同。

When I use the set the state using the value (as I need to) then I don't know how to show the label without having to write a function to map this. 当我使用set(状态)使用值(需要时)时,我不知道如何显示标签而不必编写函数来映射此标签。 Is anything built into the library to handle this? 库中是否内置任何东西可以处理此问题?

See link to a code sandbox here 在此处查看链接到代码沙箱

And below is the code showing this issue more clearly. 下面的代码更清楚地显示了此问题。 Let me know if any clarity is required? 让我知道是否需要澄清?

const options = [
  {
    label: "Chelsea Fc",
    value: "CFC"
  },
  {
    label: "Man Utd Fc",
    value: "MUFC"
  }
];

function App() {
  const [team, setTeam] = useState("");

  return (
    <React.Fragment>
      <button onClick={() => setTeam("MUFC")}>Set team to Man Utd</button>
      <Select
        value={{ label: team }}
        options={options}
        onChange={item => setTeam(item.value)}
      />
    </React.Fragment>
  );
}

Try update the onChange function: 尝试更新onChange函数:

onChange={item => setTeam(item.label)}

Or add a function to get the label: 或添加一个函数来获取标签:

const [team, setTeam] = useState("");

const getLabel = team => {
 if (team.length > 0) {
  const selected = options.filter(option => option.value === team);
  return selected[0].label;
 }
};

return (
  <div className="App">
    <button onClick={() => setTeam("MUFC")}>Set to Man Utd</button>
    <Select
      value={{ label: getLabel(team) }}
      options={options}
      onChange={item => setTeam(item.value)}
    />
  </div>
);

I think you need to map it yourself unfortunately, react-select accepts an object into the value prop. 我认为您需要自己映射它, react-select一个对象接受为value属性。

I'd make the following changes personally: 我将亲自进行以下更改:

const [team, setTeam] = useState(options[0]); (use whatever option you want as the default team to be displayed, or null for no default) (使用您想要显示的默认团队的任何选项;如果没有默认值,则使用null

Find the required option to set the value for: 查找所需的选项以设置以下值:

<button
  onClick={() => setTeam(options.find(option => option.value === "MUFC"))}
>

or hardcode it: 或硬编码:

<button
  onClick={() => setTeam(options[1])}
>

make it so that the Select uses the team from state as value, and onChange you simply set the team to the item itself 使Select使用状态中的团队作为值,而onChange只需将团队设置为项目本身

<Select
  value={team}
  options={options}
  onChange={item => setTeam(item)}
/>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM