我在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>
)
}
});
我真的很想了解这里发生了什么,也许是“正确”的做法。
答案 0 :(得分:25)
您无法从渲染函数返回多个元素(如map函数返回的数组)。此外,你错过了一个return语句。试试这个:
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>
);
}
});