子组件
'use strict'
import React from 'react';
class Comment extends React.Component {
render() {
return (
<div className="comment">
<div className="content">
<span className="author">{this.props.author}</span>
<div className="metadata">
<span className="date">{this.props.date}</span>
</div>
<div className="text">{this.props.children}</div>
</div>
</div>
)
}
}
export { Comment as default }; //输出CommentBox组件作为默认的东西
父组件
'use strict'
import React from 'react'
import Comment from './Comment'
class CommentList extends React.Component{
render() {
return (
<div>
<Comment author="lff" date="5 minutes">11111111</Comment>
<Comment author="ffl" date="3 minutes">2222</Comment>
</div>
)
}
}
export { CommentList as default }; //输出CommentBox组件作为默认的东西
从上一级组件中获取数据
- 在main.js文件中存在数据
var comments = [
{"author": "lff", "date": "5 minutes", "text": "11111"},
{"author": "ffl", "date": "3 minutes", "text": "22222"}
];
ReactDom.render(
<CommentBox data={comments}/>,
document.getElementById('app')
) ;
- 在CommentBox组件中获取main数据
<CommentList data = {this.props.data} />
- 在CommentList组件中循环展示
class CommentList extends React.Component{
render() {
let commentNodes = this.props.data.map(comment => {
return(
<Comment author={comment.author} date={comment.date}>{comment.text}</Comment>
)
})
return (
<div>
{commentNodes}
</div>
)
}
}
显示结果与原相同
从服务端获取数据
main文件获取数据路径改变
<CommentBox url="app/comments.json"/>