forked from piliyu/react-getting-started
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.jsx
executable file
·120 lines (101 loc) · 2.6 KB
/
app.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
class Comment extends React.Component {
render() {
return (
<div>
<div className="comment-body">
{this.props.children}
</div>
<div className="comment-author">
- {this.props.author}
</div>
</div>
);
}
}
class CommentForm extends React.Component {
handleSubmit(e) {
e.preventDefault();
const author = this.refs.author.getDOMNode().value.trim();
const body = this.refs.body.getDOMNode().value.trim();
const form = this.refs.form.getDOMNode();
this.props.onSubmit({author: author, body: body});
form.reset();
}
render() {
return (
<form className="comment-form" ref="form" onSubmit={e => {this.handleSubmit(e)}}>
<input type="text" placeholder="Your name" ref="author"/>
<input type="text" placeholder="Input your comment" ref="body"/>
<input type="submit" value="Add Comment"/>
</form>
);
}
}
class CommentList extends React.Component {
render() {
var commentsNode = this.props.comments.map(function(comment, index) {
return <Comment key={'comment-' + index} author={comment.author}>{comment.body}</Comment>
});
return (
<div className="comment-list">
{commentsNode}
</div>
);
}
}
class CommentBox extends React.Component {
constructor(props) {
super();
this.state = {
comments: props.comments || []
};
}
loadDataFromServer() {
$.ajax({
url: this.props.url,
dataType: "json",
success: comments => {
this.setState({comments: comments});
},
error: (xhr, status, err) => {
console.log(err.toString());
}
});
}
componentDidMount() {
this.loadDataFromServer();
}
handleNewComment(comment) {
const comments = this.state.comments;
const newComments = comments.concat([comment]);
this.setState({comments: newComments});
setTimeout(() => {
$.ajax({
url: this.props.url,
dataType: "json",
type: "POST",
data: comment,
success: comments => {
this.setState({comments: comments});
},
error: (xhr, status, err) => {
console.log(err.toString());
this.setState({comments: comments});
}
});
}, 2000);
}
render() {
return (
<div className="comment-box">
<h1>Comments</h1>
<CommentList comments={this.state.comments}/>
<CommentForm onSubmit={comment => this.handleNewComment(comment)}/>
</div>
);
}
}
box = React.render(
<CommentBox url="comments.json"/>,
document.getElementById('content')
);