Refs

头像
小编
    阅读 2 分钟
    Refs提供了一种访问DOM节点或在render方法中创建的React元素的方法。

    refs React组件中非常特殊的props,可以附加在任何一个组件上。组件被调用时会新建一个该组件的实例,而refs就会指向这个实例。

    react\lib\ReactBaseClasses.js文件中,可以看出每个组件都存在refs属性。

    /**
     * Base class helpers for the updating state of a component.
     */
    function ReactComponent(props, context, updater) {
      this.props = props;
      this.context = context;
      this.refs = emptyObject;
      // We initialize the default updater but the real one gets injected by the
      // renderer.
      this.updater = updater || ReactNoopUpdateQueue;
    }

    在React组件上添加refs

    1.使用字符串的方式添加refs
    格式:ref='string'

    import React, { Component } from 'react';
    import './App.css';
    import ReactDOM from 'react-dom';
    
    class Children extends Component {
      render() {
        return <div>
          子组件
        </div>
      }
    }
    class App extends Component {s
    
      render() {
        return (
          <div className="App">
              {/* 使用字符串方式 */}
            <Children ref='children' />
          </div>
        );
      }
    
      componentDidMount() {
        console.log(this);
        console.log('*******************************');
        console.log(this.refs.children);
      }
    }

    输出结果:
    在这里插入图片描述

    refs 可以是字符串,同样可以是回调函数。

    2.使用 回调函数 的方式添加refs
    render方法修改如下:

    render() {
        return (
          <div className="App">
              {/* 使用字符串方式 */}
            {/* <Children ref='childern' /> */}
            {/* 使用回调函数方式 */}
            <Children ref={ref=>this.childrenRef=ref} />
          </div>
        );
      }

    在这里插入图片描述

    想要获取当前React组件的实例(引用)可以使用this,获取所拥有子组件的实例(引用)可以使用refs

    React组件上添加refs,获取到的是组件的实例。而如果在原生的Dom组件上添加refs获取到的事什么呢?接着看

    在DOM元素上添加refs

    class App extends Component {
    
      constructor(props){
        super(props);
      }
    
      render() {
        return (
          <div className="App">
            <input type='text' ref='input'/>
          </div>
        );
      }
    
      componentDidMount() {
        console.log(this);
        console.log('*******************************');
        console.log(this.refs.input);
      }
    }

    结果如下:
    在这里插入图片描述

    使用回调函数同理,获取到的都是DOM节点。

    Refs 和函数组件

    refs无法应用于函数组件(无状态组件),因为函数组件挂载时只是方法调用,没有新建实例。

    如果需要引用它,则应该将组件转换为类,就像您需要生命周期方法或状态时一样。

    但是,只要引用DOM元素或类组件,就可以在函数组件中使用ref属性

    参考文档

    Refs and the DOM
    《深入React技术栈》


    小编
    34 声望6 粉丝

    原-Android工程师