简体   繁体   中英

Failed to compile React

I'm pretty sure I just don't have proper syntax but an't seem to figure out the correct syntax. Here's my code (it is inside of a return() and that return is inside of a render(){} along with html.

<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>

I am very new to this so any help would be super helpful, thanks!

You are pushing to an answers array inside of your JSX but never using it. You could instead push to the array before your return statement and then use it in the 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>
  );
});

Alternatively, you could use 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM