class Reservation extends React.Component { constructor(props) { super(props); this.state = { isGoing: true, numberOfGuests: 2, value: ‘‘ }; this.handleInputChange = this.handleInputChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleChange = this.handleChange.bind(this); } handleInputChange(event) { const target = event.target; const value = target.type === ‘checkbox‘ ? target.checked : target.value; const name = target.name; this.setState({ [name]: value }); } handleChange(event) { this.setState({value: event.target.value}); } handleSubmit(event) { alert(‘A name was submitted: ‘ + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Is going: <input name="isGoing" type="checkbox" checked={this.state.isGoing} onChange={this.handleInputChange} /> </label> <br /> <label> Number of guests: <input name="numberOfGuests" type="number" value={this.state.numberOfGuests} onChange={this.handleInputChange} /> </label> <br /> <label> Name : <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <Reservation />, document.getElementById(‘root‘) );
原文地址:https://www.cnblogs.com/Lolita-web/p/10351670.html
时间: 2024-10-20 19:28:08