zoukankan      html  css  js  c++  java
  • react表单处理 非受控组件

    没有和state数据源进行关联的表单项,而是借助ref,使用元素DOM方式获取表单元素值

    使用步骤

    • 调用 React.createRef() 方法创建ref对象
    • 将创建好的 ref 对象添加到文本框中
    • 通过ref对象获取到文本框的值

    class App extends React.Component {

      constructor(props){

        super(props)

        //创建 ref

        this.username = React.createRef()

      }

      // 获取文本框的值

      fn =() => {

        console.log(this.username.current.value)

      }

      render(){

        return (

            <div>

              <input type ="text" ref={this.username} />

              <button onClick ={this.fn}>获取值</button>

            </div>

        )

      }

    import React, { Component, createRef } from 'react'
    // import React, { Component } from 'react'
    
    export default class User3 extends Component {
    
      // 构造方法
      constructor(props) {
        super(props);
        // 定义一个用户的引用
        this.username = createRef()
      }
    
      addUser() {
        console.log(this.username.current.value);
      }
    
      render() {
        return (
          <div>
            <div>
              {/* 非受控组件 */}
              <input type="text" ref={this.username} />
            </div>
    
            <div>
              <button onClick={this.addUser.bind(this)}>添加用户</button>
            </div>
    
          </div>
        )
      }
    
    
    
    
    
    }

    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    winphone 开发学习笔记(1)
    Performance testing of web application
    每天几步一点点
    其实做测试也不是想象中的简单
    【2019杭州集训12.09】向量
    【2019杭州集训】12.09训练总结
    【2019杭州集训】12.08训练总结
    burnside定理学习小计
    【CSP-S2019D2T3】树的重心
    【CSP-S2019D1T3】树上的数
  • 原文地址:https://www.cnblogs.com/ht955/p/14667945.html
Copyright © 2011-2022 走看看