受控组件
class NameForm extends React.Component { constructor(props) { super(props); this.state = {value: ''}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(event) { const inputValue = event.target.value.replace(/\s/g,''); let str1 = inputValue.substring(0,3); let str2 = inputValue.substring(3,7); let str3 = inputValue.substring(7,11); str2 ?str2 =" "+ str2:null; str3 ?str3 =" "+ str3:null; this.setState({value: str1+str2+str3}); } handleSubmit(event) { alert('A name was submitted: ' + this.state.value); event.preventDefault(); } render() { return ( <form onSubmit={this.handleSubmit}> <label> Name: <input type="text" value={this.state.value} onChange={this.handleChange} /> </label> <input type="submit" value="Submit" /> </form> ); } } ReactDOM.render( <NameForm />, document.getElementById('root') );