从 JSON 填充 MUI Select 菜单项

Populate MUI Select menu items from JSON

我正在尝试使用 API 的 JSON 响应中的选项来填充 MUI select。目前,所有 Choices 都被推入 Select 中的一个 MenuItem

这些选择将来可能会改变,所以我想避免对它们进行硬编码。

如何应用 .mapMenuItems 分别显示 JSON Choices 而不是让它们显示在同一行上。

这是我的 JSON,下面是我显示所有其他数据的方式。

{
  "question_groups": [
    {
      "GroupName": "DDD",
      "questions": [
        {
          "Question": "1. Do you want a Drink?",
          "QuestionType": "Single Choice",
          "Response": null,
          "Choices": [
            "Yes",
            "No"
          ]
        }
      ],
      "SizingId": null
    },
}
const SelectQuestion = ({ question }) => {
  return (
    <Box>
      <TextField value={question?.Question || ""} />
      <Select label="Question" >
        <MenuItem value={question?.Choices || ""}>{question?.Choices || ""}</MenuItem>
      </Select>
      <Divider />
    </Box>
  );
};

const TextQuestion = ({ question }) => {
  return (
    <Box>
      <TextField />
      <TextField />
      <Divider />
    </Box>
  );
};

const questionComps = questions["question_groups"]?.map((group, i) => {
  return group["questions"]?.map((question, i) => {
    return question["QuestionType"] === "Text" ? (
      <TextQuestion key={`${i}${question.Question}`} question={question} />
    ) : (
      <SelectQuestion key={`${i}${question.Question}`} question={question} />
    );
  });
});

您应该通过映射 "Choices" 选项来更改 SelectQuestion 组件,并相应地渲染 MenuItem-s。

const SelectQuestion = ({ question }) => {
  return (
    <Box>
      <TextField value={question?.Question || ""} />
      <Select label="Question">
        {question.Choices.map((choice) => (
          <MenuItem key={choice} value={choice}>
            {choice}
          </MenuItem>
        ))}
      </Select>
      <Divider />
    </Box>
  );
};

Demo