• react中refs详解


    https://zh-hans.reactjs.org/docs/refs-and-the-dom.html

    字符串形式ref

    1 <input ref="myinput" type="text" placeholder="字符串形式的ref" />
    2 <button onClick={this.handleClick}>点击</button>
    3 
    4   handleClick = () => {
    5     console.log(this.refs.myinput.value);
    6   };

    回调函数形式ref

    关于回调 refs 的说明:

    如果 ref 回调函数是以内联函数的方式定义的,在更新过程中它会被执行两次,第一次传入参数 null,然后第二次会传入参数 DOM 元素。这是因为在每次渲染时会创建一个新的函数实例,所以 React 清空旧的 ref 并且设置新的。通过将 ref 的回调函数定义成 class 的绑定函数的方式可以避免上述问题,但是大多数情况下它是无关紧要的

    1 <input ref={(e) => {this.inputvalue = e; console.log(e)} } type="text" placeholder="回调函数形式的ref"/>
    2 <button onClick={this.handleClick1}>点击</button>
    3 
    4   handleClick1 = () => {
    5     console.log(this.inputvalue.value);
    6   };
    <input ref={this.saveinput} type="text" placeholder="回调函数形式2的ref"/>
    <button onClick={this.handleClick1}>点击</button>
    
      saveinput = (e) => {
        this.inputvalue = e
      }
      handleClick1 = () => {
        console.log(this.inputvalue.value);
      };

    React.createRef形式

    1 myref = React.createRef()   //createRef的ref
    2 <input ref={this.myref} type="text" placeholder="createRef的ref"/>
    3         <button onClick={this.handlechangerefs}>createRef的ref</button>
    4 
    5   handlechangerefs = () => {
    6     console.log(this.myref.current.value)
    7   }
  • 相关阅读:
    【css】怎么让Chrome支持小于12px 的文字
    java操作linux,调用shell命令
    20个非常有用的Java程序片段
    Java集合详解
    SVN使用指南
    利用SQL语句查询数据库中所有表
    HttpClient-03Http状态管理
    HttpClient-02连接管理
    HttpClient-01基本概念
    IDEA安装插件
  • 原文地址:https://www.cnblogs.com/shun1015/p/14471606.html
Copyright © 2020-2023  润新知