首页 > 解决方案 > 编译反应失败

问题描述

我很确定我只是没有正确的语法,但似乎没有弄清楚正确的语法。这是我的代码(它在 a 内部,return()并且 returnrender(){}和 html 一起在 a 内部。

<div className="questions">
  Now let's add some questions... <br />
  {// This is where we loop through our questions to
  // add them to the DOM.
  this.state.questions.map(question => {
    return (
      <div>
        {question}
        {
          for (var i = 0; i < 4; i++) {
            answers.push(
              <input 
                type="text"
                onChange={this.handleChange}
                name={uuid()}
              />
            );
          }
        }
      </div>
    );
  })
</div>

我对此很陌生,所以任何帮助都会非常有帮助,谢谢!

标签: javascriptreactjs

解决方案


您正在推送到answersJSX 内部的一个数组,但从不使用它。您可以改为在 return 语句之前推送到数组,然后在 JSX 中使用它。

this.state.questions.map(question => {
  const answers = [];

  for (var i = 0; i < 4; i++) {
    answers.push(
      <input type="text" onChange={this.handleChange} />
    );
  }

  return (
    <div>
      {question}
      {answers}
    </div>
  );
});

或者,您可以使用Array.from

<div className="questions">
  Now let's add some questions... <br />
  {this.state.questions.map(question => {
    return (
      <div>
        {question}
        {Array.from({ length: 4 }, () => (
          <input type="text" onChange={this.handleChange} />
        ))}
      </div>
    );
  })}
</div>

推荐阅读