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>
        )
      }
    
    
    
    
    
    }

    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    博客园随笔备份Java脚本
    vue 获取 referer
    EntityFramework的天坑
    清空stringbuilder
    相关的验证的正则表达式
    清空StringBuilder的三种方法及效率
    oracle中的字符串函数详解
    浅谈C# application.DoEvent作用
    C# 简单Tcp通信demo
    C#中http请求下载的常用方式demo
  • 原文地址:https://www.cnblogs.com/ht955/p/14667945.html
Copyright © 2011-2022 走看看