Skip to content

Commit

Permalink
Use controlled components for form inputs
Browse files Browse the repository at this point in the history
  • Loading branch information
yangshun committed Nov 18, 2015
1 parent aa6e9a8 commit 91abec6
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions public/scripts/example.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,22 +100,40 @@ var CommentList = React.createClass({
});

var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.refs.author.value.trim();
var text = this.refs.text.value.trim();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.refs.author.value = '';
this.refs.text.value = '';
this.setState({author: '', text: ''});
},
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="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>
);
Expand Down

0 comments on commit 91abec6

Please sign in to comment.