我有很多td
。单击每个 td 时,我想渲染一个全新的组件。我该怎么做?
Compon1
render
方法如下所示:
<tbody>
{this.props.comments.map((comment, i) =>
<tr>
<td onClick={() => <Comp2 passOnData={comment}}><p>comment.text</p></td>
</tr>
)}
</tbody>
我希望当我点击每个 td
时,应该呈现 Comp2
,但事实并非如此。
但是它也不会在控制台中抛出任何错误/警告。
由于我是新手,所以我可能会以错误的方式这样做;
最佳答案
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>;
}
});
关于javascript - 从其他组件初始化另一个 react 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33594244/