Created
January 23, 2016 08:46
-
-
Save StevenJL/2c72497564ebbc940128 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var CommentBox = React.createClass({ | |
| loadCommentsFromServer: function() { | |
| ... | |
| }, | |
| handleCommentSubmit: function(comment) { | |
| // this callback POSTs the comment to the server | |
| $.ajax({ | |
| url: this.props.url, | |
| dataType: 'json', | |
| type: 'POST', | |
| data: comment, | |
| success: function(data) { | |
| // then it sets the state, but remember, setting the state | |
| // will automatically make this component render | |
| // which will also re-render the comment list | |
| // so the comment list will automatically refresh upon submission | |
| this.setState({data: data}); | |
| }.bind(this), | |
| error: function(xhr, status, err) { | |
| console.error(this.props.url, status, err.toString()); | |
| }.bind(this) | |
| }); | |
| }, | |
| getInitialState: function() { | |
| ... | |
| }, | |
| componentDidMount: function() { | |
| ... | |
| }, | |
| render: function() { | |
| return ( | |
| <div className="commentBox"> | |
| <h1>Comments</h1> | |
| <CommentList data={this.state.data} /> | |
| <CommentForm onCommentSubmit={this.handleCommentSubmit} /> | |
| </div> | |
| ); | |
| } | |
| }); | |
| var CommentForm = React.createClass({ | |
| getInitialState: function() { | |
| ... | |
| }, | |
| handleAuthorChange: function(e) { | |
| ... | |
| }, | |
| handleTextChange: function(e) { | |
| ... | |
| }, | |
| handleSubmit: function(e) { | |
| e.preventDefault(); | |
| var author = this.state.author.trim(); | |
| var text = this.state.text.trim(); | |
| if (!text || !author) { | |
| return; | |
| } | |
| // this onCommentSubmit is really the handleCommentSubmit from the CommentBox component | |
| this.props.onCommentSubmit({author: author, text: text}); | |
| this.setState({author: '', text: ''}); | |
| }, | |
| render: function() { | |
| return ( | |
| <form className="commentForm" onSubmit={this.handleSubmit}> | |
| <input | |
| type="text" | |
| placeholder="Your name" | |
| value={this.state.author} | |
| onChange={this.handleAuthorChange} | |
| /> | |
| <input | |
| type="text" | |
| placeholder="Say something..." | |
| value={this.state.text} | |
| onChange={this.handleTextChange} | |
| /> | |
| <input type="submit" value="Post" /> | |
| </form> | |
| ); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment