Refs 提供了一种方式,允许我们访问 DOM 节点或在 render 方法中创建的 React 元素。
我个人觉得最简单的理解就是React 提供了一个属性值ref 让你存储你想要操作组件的地址
e.g.
(案例目前没有验证,不知道有没有写错)
//使用js原生写组件操作
class Demo extends React.Component{
demoTest = () =>{
const input = document.getElementById('test');
alert(input.value);
}
render(){
return(
<div>
<input id="test" type = "text">
<button onClick = {this.demoTest}></button>
<div>
)
}
}
// 使用ref进行操作
class Demo extends React.Component{
demoTest = () =>{
alert(this.ref.test);
}
render(){
return(
<div>
<input ref="test" type = "text">
<button onClick = {this.demoTest}></button>
<div>
)
}
}
通过上述两个代码可以简单发现,ref就是React提供了一个方法,去存储你想要操作的对象节点。使操作起来更加方便,当然背后的原理和原生的还是有很多区别的。
refs提供以下的三种(简略写写,具体官方文档有说明)Refs and the DOM – React
1. 字符串的refs
<button ref="test"></button>
2. 回调形式的refs
<button ref = {c=>this.test = c}>
//使用类的方式进行回调
saveRef = (c)=>{
this.test = c;
}
render(){
return(
<button ref={this.saveRef}>
)
}
3. createRef
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
createRef调用后可以返回一个容器,该容器可以存储被ref所标识的节点,该容器是唯一的。
ref 的值根据节点的类型而有所不同:
- 当
ref
属性用于 HTML 元素时,构造函数中使用React.createRef()
创建的ref
接收底层 DOM 元素作为其current
属性。- 当
ref
属性用于自定义 class 组件时,ref
对象接收组件的挂载实例作为其current
属性。- 你不能在函数组件上使用
ref
属性,因为他们没有实例。
至于最后一点,简单而言就是必须有一个值,不然会无法被渲染,会无法获取对于的值的,官方文档有具体案例解释。如果想要函数执行其实也许,需要对函数进行条件判断,当然前提是那样做还是可以渲染成功