非受控组件:现用现取
// 创建组件 class Login extends React.Component{ handleSubmit = (event) => { event.preventDefault() alert(`用户名是${this.username.value},密码是${this.password.value}`) } render() { return ( <form onSubmit={this.handleSubmit}> 用户名:<input type="text" ref={c => this.username = c} name="username"/> 密码:<input type="password" ref={c => this.password = c} name="password"/> <button>登录</button> </form> ) } } ReactDOM.render(<Login/>, document.getElementById('test'))
受控组件:类似Vue的双向绑定,随着数据的变化维护到状态中
// 创建组件 class Login extends React.Component{ state = { username: '', password: '' } saveUserName = (event) => { this.setState({username: event.target.value}) } savePassword = (event) => { this.setState({password: event.target.value}) } handleSubmit = (event) => { event.preventDefault() // 阻止表单提交 const {username, password} = this.state alert(`用户名是${username},密码是${password}`) } render() { return ( <form onSubmit={this.handleSubmit}> 用户名:<input type="text" onChange={this.saveUserName} name="username"/> 密码:<input type="password" onChange={this.savePassword} name="password"/> <button>登录</button> </form> ) } } ReactDOM.render(<Login/>, document.getElementById('test'))
由于 React 官方建议 尽量少用 ref, 所以我们多写 受控组件