Refs

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技术栈》

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值