From 91abec61ef61de2b7a6229ba65fb7b9804cf72db Mon Sep 17 00:00:00 2001 From: Tay Yang Shun Date: Wed, 18 Nov 2015 14:55:06 +0800 Subject: [PATCH] Use controlled components for form inputs --- public/scripts/example.js | 30 ++++++++++++++++++++++++------ 1 file changed, 24 insertions(+), 6 deletions(-) diff --git a/public/scripts/example.js b/public/scripts/example.js index a3e5bc20..c249427a 100644 --- a/public/scripts/example.js +++ b/public/scripts/example.js @@ -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 (
- - + +
);