How does React handle events?
React attaches event handlers to components using a camelCase naming convention. We attach onChange handlers to the two <input> elements. Now, as the user enters text into the <input> fields, the attached onChange callbacks are fired and the state of the component is modified. Subsequently, the rendered value of the input element will be updated to reflect the current component state.
(The astute reader may be surprised that these event handlers work as described, given that the method references are not explicitly bound to this. React.createClass(…) automatically binds each method to its component instance, obviating the need for explicit binding.)
return (
<button onClick={() => this.setState({ liked: true })}>
Like
</button>
);
import PropTypes from 'prop-types'
const Button = ({ color, text, onClick }) => {
return (
<button
onClick={onClick}
style={{ backgroundColor: color }}
className='btn'
>
{text}
</button>
)
}
Button.defaultProps = {
color: 'steelblue',
}
Button.propTypes = {
text: PropTypes.string,
color: PropTypes.string,
onClick: PropTypes.func,
}
export default Button
How can we handle form submit?
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.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
// TODO: send request to the server
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>
);
}
});
We attach an onSubmit handler to the form that clears the form fields when the form is submitted with valid input. Call preventDefault() on the event to prevent the browser's default action of submitting the form.