我有很多td
个。点击每个td
,我想渲染一个全新的组件。我该怎么做?
Compon1
render
方法如下所示:
<tbody>
{this.props.comments.map((comment, i) =>
<tr>
<td onClick={() => <Comp2 passOnData={comment}}><p>comment.text</p></td>
</tr>
)}
</tbody>
我希望点击每个Comp2
时都会呈现td
,但这种情况不会发生。
但是它也没有在控制台中抛出任何错误/警告。
由于我有新的反应,我可能会以错误的方式这样做;
答案 0 :(得分:1)
var Comment = React.createClass({
render: function() {
let comments = this.props.comment.child.map((comment, index) => {
return <li key={index}>{comment}</li>;
});
return <ul>
{ comments }
</ul>;
}
});
var Comments = React.createClass({
getInitialState: function() {
return {
comments: this.props.comments
}
},
handleToggle: function (comment) {
let comments = this.state.comments.map((el) => {
el.isActive = (el.id === comment.id) ? !el.isActive : el.isActive
return el;
});
this.setState({ comments: comments });
},
render: function() {
let comments = this.state.comments.map((comment, i) => {
return <tr key={i}>
<td onClick={ this.handleToggle.bind(this, comment) }>
<p>{ comment.text }</p>
{ comment.isActive ? <Comment comment={comment} /> : null }
</td>
</tr>;
});
return <table>
<tbody>{ comments }</tbody>
</table>;
}
});