import React from 'react';
import ReactDOM from 'react-dom';
// 列表父组件
let CommentList = React.createClass({
render (){
// 循环输出列表子组件
let CommentNodes = this.props.data.map(comment => {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return(
<div className="commentList">
{CommentNodes}
</div>
);
}
});
// 表单组件
let CommentForm = React.createClass({
// 绑定状态值 用于在当前组件传递参数
getInitialState (){
return {
author : '',
text : ''
}
},
handleAuthorChange (e){
this.setState({author : e.target.value});
},
handleTextChange (e){
this.setState({text : e.target.value});
},
handleSubmit (e){
e.preventDefault();
let author = this.state.author.trim();
let text = this.state.text.trim();
if(!text || !author) return false;
// 父组件传递的方法 用于更新提交的数据
this.props.onCommentSubmit({id : 0, author : author, text : text});
this.setState({author : '', text : ''});
},
render (){
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type = "text"
placeholder = "Your name"
value = {this.state.author}
onChange = {this.handleAuthorChange}
/>
<input
type = "text"
placeholder = "content"
value = {this.state.text}
onChange = {this.handleTextChange}
/>
<button>Post</button>
</form>
);
}
});
// 列表子组件
let Comment = React.createClass({
render (){
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
// 获取嵌套的元素
{this.props.children}
</div>
);
}
});
// 总组件
let CommentBox = React.createClass({
getInitialState (){
return {
data : []
}
},
componentDidMount (){
let data = [
{id:1, author:'小蓝', text:'第一条数据'},
{id:2, author:'小花', text:'第二条数据'}
];
this.setState({
data : data
});
},
handleCommentSubmit (comment){
debugger;
let comments = this.state.data;
comment.id = Date.now();
let newComments = comments.concat([comment]);
this.setState({data : newComments});
},
render (){
return (
<div className="commentBox">
<h1>CommentBox 组件</h1>
// 列表组件
<CommentList data={this.state.data}></CommentList>
// 表单组件
// onCommentSubmit 传递onCommentSubmit方法给子组件
<CommentForm onCommentSubmit={this.handleCommentSubmit}></CommentForm>
</div>
);
}
});
ReactDOM.render(
<CommentBox></CommentBox>,
document.querySelector('.content')
);