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

    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    TCP/IP——IP网络协议简记
    TCP/IP——基础概念简记
    TCP/IP——链路层简记
    linux——(8)数据流重定向、管道命令
    linux——(7)了解shell
    linux——(6)vim与vi
    linux——(5)文件与文件系统的压缩与打包
    linux——(4)磁盘与文件系统管理
    linux——(3)文件与目录管理
    大数据--Spark原理
  • 原文地址:https://www.cnblogs.com/ht955/p/14667945.html
Copyright © 2020-2023  润新知