Skip to content

Commit 2494d9f

Browse files
committed
Merge pull request reactjs#101 from yangshun/controlled-components
Use controlled components for form inputs
2 parents aa6e9a8 + 91abec6 commit 2494d9f

File tree

1 file changed

+24
-6
lines changed

1 file changed

+24
-6
lines changed

public/scripts/example.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,22 +100,40 @@ var CommentList = React.createClass({
100100
});
101101

102102
var CommentForm = React.createClass({
103+
getInitialState: function() {
104+
return {author: '', text: ''};
105+
},
106+
handleAuthorChange: function(e) {
107+
this.setState({author: e.target.value});
108+
},
109+
handleTextChange: function(e) {
110+
this.setState({text: e.target.value});
111+
},
103112
handleSubmit: function(e) {
104113
e.preventDefault();
105-
var author = this.refs.author.value.trim();
106-
var text = this.refs.text.value.trim();
114+
var author = this.state.author.trim();
115+
var text = this.state.text.trim();
107116
if (!text || !author) {
108117
return;
109118
}
110119
this.props.onCommentSubmit({author: author, text: text});
111-
this.refs.author.value = '';
112-
this.refs.text.value = '';
120+
this.setState({author: '', text: ''});
113121
},
114122
render: function() {
115123
return (
116124
<form className="commentForm" onSubmit={this.handleSubmit}>
117-
<input type="text" placeholder="Your name" ref="author" />
118-
<input type="text" placeholder="Say something..." ref="text" />
125+
<input
126+
type="text"
127+
placeholder="Your name"
128+
value={this.state.author}
129+
onChange={this.handleAuthorChange}
130+
/>
131+
<input
132+
type="text"
133+
placeholder="Say something..."
134+
value={this.state.text}
135+
onChange={this.handleTextChange}
136+
/>
119137
<input type="submit" value="Post" />
120138
</form>
121139
);

0 commit comments

Comments
 (0)