108 lines
2.7 KiB
JavaScript
108 lines
2.7 KiB
JavaScript
/**
|
|
* Created by guange on 16/3/19.
|
|
*/
|
|
|
|
|
|
|
|
|
|
var CommentBox = React.createClass({
|
|
|
|
loadFromServer: function(){
|
|
$.ajax({
|
|
url: this.props.url,
|
|
dataType: 'json',
|
|
success: function(data){
|
|
this.setState({data: data});
|
|
}.bind(this),
|
|
error: function(xhr,status,err){
|
|
console.error(this.props.url, status, err.toString());
|
|
}.bind(this)
|
|
});
|
|
},
|
|
onCommentSubmit: function(comment){
|
|
console.log(comment);
|
|
},
|
|
getInitialState: function(){
|
|
return {data: []};
|
|
},
|
|
componentDidMount: function(){
|
|
this.loadFromServer();
|
|
setInterval(this.loadFromServer, 2000);
|
|
},
|
|
render: function(){
|
|
return(
|
|
<div className="commentBox">
|
|
<CommentForm onCommentSubmit={this.onCommentSubmit}/>
|
|
<CommentList data={this.state.data}/>
|
|
</div>
|
|
);
|
|
}
|
|
});
|
|
|
|
var CommentList = React.createClass({
|
|
render: function(){
|
|
|
|
var commentNodes = this.props.data.map(function(comment){
|
|
return (
|
|
<Comment author={comment.author}>
|
|
{comment.text}
|
|
</Comment>
|
|
)
|
|
});
|
|
|
|
return (
|
|
<div className="commentList">
|
|
{commentNodes}
|
|
</div>
|
|
);
|
|
}
|
|
});
|
|
|
|
var CommentForm = React.createClass({
|
|
handleSubmit: function(e){
|
|
e.preventDefault();
|
|
|
|
var author = this.refs.author.value.trim();
|
|
var text = this.refs.text.value.trim();
|
|
if(!text || !author){
|
|
return;
|
|
}
|
|
|
|
this.props.onCommentSubmit({author: author, text: text});
|
|
|
|
this.refs.author.value = '';
|
|
this.refs.text.value = '';
|
|
return;
|
|
},
|
|
render: function(){
|
|
return (
|
|
<form className="commentForm" onSubmit={this.handleSubmit}>
|
|
<input type="text" placeholder="Your name" ref="author" />
|
|
<input type="text" placeholder="Say something..." ref="text" />
|
|
<input type="submit" value="Post" />
|
|
</form>
|
|
);
|
|
}
|
|
});
|
|
|
|
|
|
var Comment = React.createClass({
|
|
|
|
rawMarkup: function() {
|
|
var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
|
|
return { __html: rawMarkup };
|
|
},
|
|
|
|
render: function(){
|
|
return (
|
|
<div className="comment">
|
|
<h2 className="commentAuthor">
|
|
{this.props.author}
|
|
</h2>
|
|
<span dangerouslySetInnerHTML={this.rawMarkup()}></span>
|
|
</div>
|
|
)
|
|
}
|
|
})
|
|
|
|
React.render(<CommentBox url="api/comment.json"/>, document.getElementById("example")); |