【问题标题】:Using enumerations in React select在 React select 中使用枚举
【发布时间】:2019-04-09 21:07:24
【问题描述】:

我想使用以下枚举在 React 中显示一个下拉列表。这个想法是防止在我的<select> 中使用随机字符串作为键。密钥应限制为Stooges.larryStooges.curlyStooges.moe

const Stooges = {
  larry: "Larry Fine",
  curly: "Curly Howard",
  moe: "Moe Howard"
};

这是我选择的代码,效果很好:

<select value={stooge} onChange={handleChange}>
  {Object.keys(Stooges).map(key => (
    <option key={key} value={key}>
      {Stooges[key]}
    </option>
  ))}
</select>

当我尝试设置下拉菜单的初始值时出现问题 - 我必须使用硬编码键:

const [stooge, setStooge] = React.useState('larry');

我可以通过选择第一个键来缓和一点:

const keys = Object.keys(Stooges);
const [stooge, setStooge] = React.useState(keys[0]);

但是,这仍然感觉不对。我无法从key[0] 看出我在选谁。

有没有更好的方法来处理这个用例中的枚举?我在 TypeScript 中尝试过字符串枚举,但它们有同样的问题:

enum Stooges {
  larry = "Larry Fine",
  curly = "Curly Howard",
  moe = "Moe Howard"
}

请查看我的 CodeSandbox here

【问题讨论】:

  • 我发现keyof Stooges 只适用于type Stooges = {...},所以我删除了我的答案:(

标签: reactjs typescript enums


【解决方案1】:

由于缺乏更好的解决方案,我采取了以下方法。我至少能够按名称选择正确的枚举:Stooges.larry.id:

const Stooges = {
  larry: {
    id: "larry",
    name: "Larry Fine"
  },
  curly: {
    id: "curly",
    name: "Curly Howard"
  },
  moe: {
    id: "moe",
    name: "Moe Howard"
  }
};

function App() {
  const [stooge, setStooge] = React.useState(Stooges.larry.id);

  const handleChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setStooge(event.target.value);
  };

  return (
    <div className="App">
      <select value={stooge} onChange={handleChange}>
        {Object.keys(Stooges).map(key => (
          <option key={key} value={key}>
            {Stooges[key].name}
          </option>
        ))}
      </select>
    </div>
  );
}

这是新的 CodeSandbox:https://codesandbox.io/embed/wqj2q94o2k

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-29
    • 2023-04-04
    • 2012-03-20
    • 2012-03-04
    相关资源
    最近更新 更多