如何在 Reactjs中显示注释或子记录。
我有以下代码,它们通过 reactjs 显示来自数组的帖子。请问我如何也显示评论。
使用 Angularjs ,我可以使用以下代码轻松实现此目标
<div ng-repeat="post in posts">
<div>
{{ post.content }}
</div>
<div ng-repeat="comment in post.comments">
<div class="comment">{{ comment.comment }}</div>
</div>
</div>
这是 Reactjs 中的主要代码。任何帮助将不胜感激。谢谢
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
rec: [
{"id":"1","content":"first post","comments":[{"comment":"first comment"}]},
{"id":"2","content":"second post","comments":[{"comment":"second comment"}]}
],
};
}
render() {
return (
<div>
<h3>Records</h3>
<ul>
{this.state.rec.map((post, i) => (
<li key = {i}>
{post.id} - {post.content}
</li>
))}
</ul>
</div>
);
}
}
ReactDOM.render( <Application /> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app">
</div>
答案 0 :(得分:0)
以下是执行此操作的一种方法的示例:
const Post = (props) => {
return (<React.Fragment><li >
{props.post.id} - {props.post.content}
</li>
<div>
{props.post.comments.map((comment, i) => (<div>{comment.comment}</div>))}
</div>
</React.Fragment>
);
};
class Application extends React.Component {
constructor(props) {
super(props);
this.state = {
rec: [
{"id":"1","content":"first post","comments":[{"comment":"first comment"}]},
{"id":"2","content":"second post","comments":[{"comment":"second comment"}, {"comment":"third comment"}]}
],
};
}
render() {
return (
<div>
<h3>Records</h3>
<ul>
{this.state.rec.map((post, i) => (
<Post post={post} key={i}/>
))}
</ul>
</div>
);
}
}
ReactDOM.render( <Application /> , document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app">
</div>