React 受控组件与非受控组件
React笔记
受控组件 (推荐)
特点: 现用现取
<body> <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> </body>
|
非受控组件
特点: 随着输入维护状态就是受控
<body> <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> </body>
|
作者: 我叫史迪奇
本文来自于:
https://sdq3.link/React-Controlled-Uncontrolle.html博客内容遵循 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 协议