我有一个答案数组,按它们所属的问题排序,如下所示:
sortedAnswers= [[Answer1, Answer2, Answer3, Answer4],[AnswerA, AnswerB, AnswerC, AnswerD]...]
我正在尝试在 React 中渲染 ListItemButton 的列表。我尝试过
<ButtonGroup fullWidth orientation='vertical' onClick={handleSubmit} onChange={handleChange} > {sortedAnswers.map((item) => <ListItemButton>{item}</ListItemButton> )} </ButtonGroup>
但它没有按预期工作,我得到了这个:
我希望每个答案都有一个 ListItemButton,因此每个问题有 4 个按钮。我怎样才能得到按钮中第一个数组的答案?
P粉2620731762023-09-07 09:55:31
根据您希望布局的外观,使用嵌套循环来迭代所有答案:
const sortedAnswers = [ [Answer1, Answer2, Answer3, Answer4], [AnswerA, AnswerB, AnswerC, AnswerD] ]; {sortedAnswers.map(answers => ( <ButtonGroup fullWidth orientation="vertical" onClick={handleSubmit} onChange={handleChange} > {answers.map(answer => ( <ListItemButton>{answer}</ListItemButton> ))} </ButtonGroup> ))}
P粉1059715142023-09-07 09:02:29
正如您提到的错误:无法读取未定义的属性(读取“地图”)
,请在映射之前添加条件检查。
{sortedAnswers.length > 0 && ( <ButtonGroup fullWidth orientation='vertical' onClick={handleSubmit} onChange={handleChange}> {sortedAnswers[0].map((answer, index) => ( <ListItemButton key={index}>{answer}</ListItemButton> ))} </ButtonGroup> )}