react 受控组件,双向绑定
学习视频:https://www.bilibili.com/video/BV1wy4y1D7JT?p=34
一、受控组件
onChange方法实现
<script type="text/babel"> //创建组件 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 onChange={this.saveUsername} type="text" name="username"/> 密码:<input onChange={this.savePassword} type="password" name="password"/> <button>登录</button> </form> ) } } //渲染组件 ReactDOM.render(<Login/>,document.getElementById('test')) </script>
每一个input都要写一个方法保存状态,对此处进一步优化:https://www.cnblogs.com/shining-feifan/p/16247122.html
二、非受控组件
<script type="text/babel"> //创建组件 class Login extends React.Component{ handleSubmit = (event)=>{ event.preventDefault() //阻止表单提交 const {username,password} = this alert(`你输入的用户名是:${username.value},你输入的密码是:${password.value}`) } render(){ return( <form onSubmit={this.handleSubmit}> 用户名:<input ref={c => this.username = c} type="text" name="username"/> 密码:<input ref={c => this.password = c} type="password" name="password"/> <button>登录</button> </form> ) } } //渲染组件 ReactDOM.render(<Login/>,document.getElementById('test')) </script>