我有一個答案數組,按它們所屬的問題排序,如下所示:
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> )}