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

    右侧打赏一下 代码改变世界一块二块也是爱
  • 相关阅读:
    Python __repr__()方法:显示属性
    Python SQLAlchemy入门教程(基本用法)
    彻底搞懂Token、Session和Cookie。
    MTV和MVC的区别
    Flask配置Cors跨域
    跨域资源共享 CORS 详解
    浏览器同源政策及其规避方法
    敏捷开发
    Nginx搭建正向代理服务器支持https
    为什么使用k8s和容器作为devops的底层平台
  • 原文地址:https://www.cnblogs.com/ht955/p/14667945.html
Copyright © 2011-2022 走看看