Refs

Refs提供了一种访问DOM节点或在render方法中创建的React元素的方法。

refsReact组件中非常特殊的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技术栈》

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • refs提供了一种方法,用于访问在render中创建的dom节点或者React元素。 在典型的React数据流中,...
    XKolento阅读 5,248评论 0 3
  • 深入JSX date:20170412笔记原文其实JSX是React.createElement(componen...
    gaoer1938阅读 12,479评论 2 35
  • refs提供了可以在render方法中访问dom节点和创建的react元素的方法。 为了良好的阅读体验,请查看gi...
    mytac阅读 3,251评论 0 1
  •   在常规的 React 数据六中,props 是父组件与子组件交互的唯一方法。如果需要改子元素,你需要用新的pr...
    果汁凉茶丶阅读 4,518评论 0 0
  • 一切都是缘分,一切都是命运,一个南方小伙跑到了遥远的大北方去上学。离开大连两年了,再没回去过,估计也不回去了,只有...
    珠江渔民阅读 5,814评论 3 6

友情链接更多精彩内容