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