zoukankan      html  css  js  c++  java
  • react中受控组件与非受控组件--

    非受控组件:随用随取

     1 render() {
     2         return (
     3             <div>
     4                 <h1>非受控组件</h1>
     5                 <form action="" onSubmit={this.handleSub}>
     6                     姓名:<input ref={(e) => {this.username = e}} type="text" name="username" /><br></br>
     7                     密码:<input ref={(e) => {this.password = e}} type="text" name="password"/><br></br>
     8                     <button>提交</button>
     9                 </form>
    10             </div>
    11         )
    12     }
    13     handleSub = (event) => {
    14         event.preventDefault()  //因为表单有个action属性,表示提交地址,默认不写绘刷新当前页面,所以说阻止默认事件,我们实际开发中是以ajax请求,做到不刷新页面的
    15         console.log(this)
    16         const {username, password} = this
    17         alert(`姓名:${username.value}, 密码:${password.value}`)
    18     }

    受控组件:输入框随着用户的输入把值维护到状态里面去,等用的时候从状态里面获取,例如vue直接利用v-model双向绑定的原理实现

     1 render() {
     2     return (
     3       <div>
     4         <h1>非受控组件</h1>
     5         <form action="" onSubmit={this.handleSub}>
     6           姓名:
     7           <input onChange={this.handlename} type="text" name="username" />
     8           密码:
     9           <input onChange={this.handleword} type="text" name="password" />
    10           <button>提交</button>
    11         </form>
    12       </div>
    13     );
    14   }
    15   handlename = (e) => {
    16     this.setState({username:e.target.value})
    17   }
    18   handleword = (e) => {
    19     this.setState({password:e.target.value})
    20   }
    21 
    22   handleSub = (event) => {
    23     event.preventDefault(); //因为表单有个action属性,表示提交地址,默认不写绘刷新当前页面,所以说阻止默认事件,我们实际开发中是以ajax请求,做到不刷新页面的
    24     console.log(this);
    25     const { username, password } = this.state;
    26     alert(`姓名:${username}, 密码:${password}`);
    27   };
  • 相关阅读:
    P1092 虫食算
    P1040 加分二叉树
    cfER76 abcd
    cf599 div2 a/b1/b2/c
    AtCoder Contest 144 DE
    Round G 2019
    luogu3084 Photo 单调队列优化DP
    luogu4234 最小差值生成树
    luogu1373 小a和uim之大逃离
    luogu1070 道路游戏 单调队列
  • 原文地址:https://www.cnblogs.com/shun1015/p/14471728.html
Copyright © 2011-2022 走看看