一、The ref callback attribute

ref:reference,父组件引用子组件

组件并不是真实的 DOM节点,而是存在于内存之中的一种数据结构,叫做虚拟DOM。只有当它插入文档以后,才会变成真实的 DOM 。根据 React 的设计,所有的 DOM 变动,都先在虚拟 DOM 上发生,然后再将实际发生变动的部分,反映在真实 DOM上,这种算法叫做DOM diff ,它可以极大提高网页的性能表现。但是,有时需要从组件获取真实 DOM 的节点,这时就要用到 ref 属性.

1.1 refs.[refName]

this.refs.[refName] 返回真实的 DOM 节点。需要注意的是,由于 this.refs.[refName] 属性获取的是真实 DOM ,所以必须等到虚拟 DOM 插入文档以后,才能使用这个属性,否则会报错。

class MyComponent extends React.Component{
handleClick(event){
this.refs.myInput.focus();
}
render(){
return (
<div>
<input type="text" ref="myInput" />
<button onClick={this.handleClick}>Focus on me</button>
</div>
)
}
}
React.render(<MyComponent/>,document.body)

1.2 ref为函数

ref 属性可以是一个回调函数,而不是一个名字。这个回调函数在组件安装后立即执行。被引用的组件作为一个参数传递,且回调函数可以立即使用这个组件,或保存供以后使用(或实现这两种行为)。比如下面这段代码,ref回调储存DOM节点的引用。

class CustomTextInput extends React.Component {
constructor(props) {
super(props);
this.focus = this.focus.bind(this);
} focus() {
// Explicitly focus the text input using the raw DOM API
this.textInput.focus();
} render() {
// Use the `ref` callback to store a reference to the text input DOM
// element in this.textInput.
return (
<div>
<input
type="text"
ref={(input) => { this.textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={this.focus}
/>
</div>
);
}
}

React将在组件mounts时调用ref回调,输入DOM元素;在组件unmount时调用ref回调,输入null。一种常见的模式是利用ref回调来访问DOM元素。如果你现在使用的是this.refs.myrefName来访问ref,建议采用上面这种回调函数的形式。

当ref属性用在一个自定义组件上,ref回调接受这个组件的mounted实例作为参数。比如,如果我们想包裹上面的CustomTextInput组件来模拟他mount后立即被单击

class AutoFocusTextInput extends React.Component {
componentDidMount() {
this.textInput.focus();
} render() {
return (
<CustomTextInput
ref={(input) => { this.textInput = input; }} />
);
}
}

你可能不会在函数组件上使用ref属性,因为函数组件没有实例,然而你可以在函数组件的render 函数中使用ref属性。

function CustomTextInput(props) {
// textInput must be declared here so the ref callback can refer to it
let textInput = null; function handleClick() {
textInput.focus();
} return (
<div>
<input
type="text"
ref={(input) => { textInput = input; }} />
<input
type="button"
value="Focus the text input"
onClick={handleClick}
/>
</div>
);
}

二、不要滥用refs

当你想使用refs时,想想是否可以用state代替。最适合设置state的地方是在层级中较高的位置设置。

Refs的更多相关文章

  1. git提示:Fatal:could not fetch refs from ....

    在git服务器上新建项目提示: Fatal:could not fetch refs from git..... 百度搜索毫无头绪,最后FQgoogle,找到这篇文章http://www.voidcn ...

  2. git rebase与 git合并(error: failed to push some refs to)解决方法

    1.遇到的问题 本地有一个git仓库,在github上新建了一个空的仓库,但是更新了REWADME.md的信息,即在github上多了一个提交. 关联远程仓库,操作顺序如下: git remote a ...

  3. 关于refs/for/ 和refs/heads/

    1.     这个不是git的规则,而是gerrit的规则, 2.     Branches, remote-tracking branches, and tags等等都是对commite的引用(re ...

  4. perl Can't use string Cxxx) as a symbol ref while "strict refs" in use at XXXX.pl错误

    今天写脚本遇到Can't use string ("bond2     Link encap:InfiniBand ") as a symbol ref while "s ...

  5. git: No refs in common and none specified; doing no

    用gitolite新建项目,clone后首次push,可能会出现:     $ git push No refs in common and none specified; doing nothing ...

  6. Refs to Components

    一.ref是通过ReactDOM.render返回的 定义在组件上的render方法返回的是一个虚拟的DOM节点,jsx返回的是一个ReactElement,ReactDOM.render返回的是一个 ...

  7. Extjs4 MVC Controlller中refs使用

    前面几篇写了一下mvc的整体使用方法,今天写一下controller中refs的试用,refs的作用类似于我们告诉controller我们的一个元素的别名,既alias,那么controller就会为 ...

  8. [React Fundamentals] Using Refs to Access Components

    When you are using React components you need to be able to access specific references to individual ...

  9. [React] React Fundamentals: Using Refs to Access Components

    When you are using React components you need to be able to access specific references to individual ...

  10. o] TortoiseGit错误 - Could not get all refs. libgit2 returned: corrupted loose reference file

    因无法追溯的同步操作错误或工程文件错误,造成Git 同步时报错: Could not get all refs. libgit2 returned: corrupted loose reference ...

随机推荐

  1. drf作业01

    api\urls from django.conf.urls import url from . import views urlpatterns = [ url(r'^cars/$',views.C ...

  2. 2018-8-10-win10-uwp-禁止编译器优化代码

    title author date CreateTime categories win10 uwp 禁止编译器优化代码 lindexi 2018-08-10 19:16:50 +0800 2018-2 ...

  3. Laravel Homestead: 403 forbidden on nginx, http://homestead.app访问不了

    起因:是因为Homestead.yaml 映射失败,一般是由于没有修改sites导致的, 正确的sites设置,类似于: 而很多人吧folders的配置看成是sites的配置了 解决方法: ①按照正确 ...

  4. 阿里云SaaS生态战略发布:成就亿级营收独角兽

    导语:本文中,阿里云智能资深技术专家黄省江从“势”“道”“术”三个方面分享了自己对于SaaS生态的理解,并介绍了SaaS加速器发布以来在产品.技术和商业侧最新的一些进展. 在321北京峰会上,阿里云公 ...

  5. bzoj 3209 花神的数论题——二进制下的数位dp

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3209 可以枚举 “1的个数是...的数有多少个” ,然后就是用组合数算在多少位里选几个1. ...

  6. selenium(4):初次尝试,通过百度进行搜索

    实现场景:打开chrome浏览器后,打开百度,再搜索栏里输入‘测试’,点击搜索按钮. 代码:定位方式,通过元素的ID. 定位技巧: ①鼠标定位需要定位的输入框,鼠标右键单击.选择检查. ②即可轻松的查 ...

  7. opencv2.4.9配置+VS2013

    参见:浅墨的(红的的为变动部分) http://blog.csdn.net/poem_qianmo/article/details/19809337 本系列文章由@浅墨_毛星云 出品,转载请注明出处. ...

  8. AJAX之再升级版PJAX

    前几天在一个大神群里提到ajax优化选项卡功能的方法上,有位低调的大神默默得打出:了解一下pjax,好奇心的驱使下,我具体查了一下pjax,不一般啊,ax结合pushState和ajax技术, 不需要 ...

  9. 洛谷P1681 最大正方形II

    P1681 最大正方形II 题目背景 忙完了学校的事,v神终于可以做他的“正事”:陪女朋友散步.一天,他和女朋友走着走着,不知不觉就来到 了一个千里无烟的地方.v神正要往回走,如发现了一块牌子,牌子上 ...

  10. POJ 2078

    16ms 解法: #include <cstdio> //using namespace std; ][]; ][]; ]; ]; int n,min,max; void solve(in ...