9

我在我的 React 渲染中遇到了持续存在的问题。

这段代码

/** @jsx React.DOM */
var AnswerRows = React.createClass({
  componentDidMount: function() {
  },
  render: function() {
    {this.props.answers.map(function(answer, i) {
      return (
        <div id="answerRow">
          <label className="AnswerText">
            <input type="checkbox" value={answer.id}  />
            {answer.text}
          </label>
        </div>
      );
    }, this)}
  }
});

var QuizTaking = React.createClass({
  componentDidMount: function() {
  },
  render: function() {
    return (
      <div className="card-holder">
        <div className="showQuestionCard x-card host">
          <h3 dangerouslySetInnerHTML={{__html: this.props.question.text}}></h3>
          <div className="answerRows">
            <AnswerRows answers={this.props.question.answers}/>
          </div>
          <div className='submitAnswers'></div>
        </div>
        <div className="paper-shadow-bottom"></div>
      </div>
    )
  }
})

会给我Invariant Violation: AnswerRows.render(): A valid ReactComponent must be returned. You may have returned undefined, an array or some other invalid object.错误。但是,这每次都有效:

/** @jsx React.DOM */

var TestIndex = React.createClass({

  propTypes: {
  },
  loadTest: function(i) {
    window.location.replace(this.props.tests[i].url.replace(".json", "/take"))
  },

  render: function () {
    return(
      <div className="testTable card-holder">
        <div className="card-contents">
          {this.props.tests.map(function(test, i) {
            return (
              <div className="testTableRow x-card host" key={test.id}>
                <label className="__TITLE">{test.title}
                  <button onClick={this.loadTest.bind(test, i)}  key={i} type="button" className="StartButton paper-button raisedButton">Start this test</button>
                </label>
                <div className="paper-shadow-bottom"></div>
              </div>
            );
          }, this)}
        </div>
      </div>
    )
  }
});

我真的很想了解这里发生了什么,也许是“正确”的方法。

4

1 回答 1

25

您不能从渲染函数返回多个元素(如 map 函数返回的数组)。另外,您缺少退货声明。尝试这个:

var AnswerRows = React.createClass({
  componentDidMount: function() {
  },
  render: function() {
    return (
      <div>
        {this.props.answers.map(function(answer, i) {
          return (
            <div id="answerRow">
              <label className="AnswerText">
                <input type="checkbox" value={answer.id}  />
                {answer.text}
              </label>
            </div>
          );
        }, this)}
      </div>
    );
  }
});
于 2014-10-17T18:05:56.690 回答