React - React版的*ngFor

看看react怎么来用循环

  • NG2 => *ngFor

let data = [
{ id: 1, author: "Pete Hunt", text: "This is one comment" },
{ id: 2, author: "Jordan Walke", text: "This is *another* comment" }
];


class CommentList extends React.Component<{ data: any[] }, any>{
render() {

let commentsNode = this.props.data.map(x => {
return (
<Comment author={x.author} key={x.id}>{x.text} </Comment>
)
})

return (
<div className="commentList">
{commentsNode}
</div>
)
}
}


//this is the root component which including other comps
class CommentBox extends React.Component<any, any> {
render() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
</div>
)
}
}

ReactDOM.render(<CommentBox data={data} />, document.getElementById("targetreact"));

数据从CommentBox的props 传入, props.data

继续传入到CommentList 的 props.data
react的jsx 循环还挺functional的 还搞起了 map

把可重复jsx 用map 变成 Array
然后直接当变量 {commentsNode},

这里有个key属性是React element的一个属性

interface Attributes {
key?: Key;
}

When React reconciles the keyed children, it will ensure that any child with key will be reordered (instead of clobbered) or destroyed (instead of reused).
key 当DOM变化的时候react内部会做一些重用,而不是重新创建 和destroy的过程.
所以对于会有增加去掉的可循环obj需要给个key