为什么我的 JSX 元素数组不会出现在我的 reactjs 渲染中?



我正在构建一个小的琐事应用程序,并尝试为每个问题插入更新的"选择"元素数组,但是当我尝试插入JSX元素数组时,数组不断显示为空白,我不知道为什么:

let choices = [];
const generateChoices = (answers) => {
for(let i = 0; i < answers.length; i++){
choices.push(<ChoiceButton key={answers[i]} value={answers[i]} clicked={(answer) => setSelectedAnswer(decodeURIComponent(answer))}>{answers[i]}</ChoiceButton>);
};
};
generateChoices(["One", "Two", "Three", "Four"]);
<BoxWrapper>
...
<Fragment>
<ChoiceForm>
{choices}
<SubmitButton isDisabled={!selectedAnswer} clicked={(e) => {e.preventDefault(); checkAnswer();}}>Submit</SubmitButton>
</ChoiceForm>
</Fragment>
...
</BoxWrapper>

从选择按钮.js:

const ChoiceButton = props => {
return (<Fragment>
<ChoiceRadio type="radio" id={props.value} name="choice" onClick={() => props.clicked(props.value)}/>
<ChoiceLabel htmlFor={props.value} correct={props.correct}>{props.children}</ChoiceLabel>
</Fragment>
)
}

据我所知,如果我做console.log(choices),它表明我有 4 个 JSX 元素,但数组在 React 调试器中显示为空白。我该如何解决这个问题?

我认为您需要遍历数组。 尝试做

{choices.map(choice=>choice)}

类似的东西。基本上,您应该通过循环数组来逐个呈现它们。

最新更新