container--------------commentBox
评论列表 ----commentList
评论内容 ---comment
评论内容 ---comment
评论列表 ----
写评论的组件 ---commentForm
container--------------
1. 获取评论数据
(1) 在服务端写 mock 模拟数据 -- 取得 API 接口的 URL 地址
(2) 在对应函数内写 ajax 请求,
在 success 中 this.setState({data:result.*})
不要忘记
- getInitialState: function() {
- return {
- data: []
- };
- },
(3) 在评论组件中循环遍历 data
- <CommentList data={this.state.data} />
- var CommentList = React.createClass({ render: function() { var commentNodes
- = this.props.data.map(function(comment) { return (
- <Comment author={comment.author} key={comment.id}>
- {comment.text}
- </Comment>
- ); }); return (
- <div className="commentList">
- {commentNodes}
- </div>
- ); }});
2. 添加评论
(1) 给每一个输入框,下拉框,分页等设置 onChange={this.*}
- getInitialState: function() {
- return {
- author: '',
- text: ''
- };
- },
(2)
- handleTextChange(e) {
- handleTextChange就是 * 对应输入框等的改变事件this.setState({
- text: e.target.value
- });
- }
(3) 在提交表单的事件中判断数据是否为空,数据的长度
同时将输入框的数据清空
- handleSubmit: function(e) {对应form组件的提交事件e.preventDefault();
- var author = this.state.author.trim();
- var text = this.state.text.trim();
- if (!text || !author) {
- return;
- } // TODO: send request to the server this.setState({author: '', text: ''}); },
(4) 通过 ajax 请求发送数据
最顶层 ---------------
- handleCommentSubmit: function(comment) {
- $.ajax({
- url: this.props.url,
- dataType: 'json',
- type: 'POST',
- data: comment,
- success: function(data) {
- this.setState({
- data: data
- });
- }.bind(this),
- error: function(xhr, status, err) {
- console.error(this.props.url, status, err.toString());
- }.bind(this)
- });
- },
- <CommentForm onCommentSubmit = {
- this.handleCommentSubmit
- }
- />/ / 在CommentForm组件内------------this.props.onCommentSubmit({
- author: author,
- text: text
- });
来源: