React中的Refs指南
有时在使用 React.js 时,您需要一个逃生舱来编写命令式代码以直接与 DOM 元素交互。 使用 React 的 createRef 方法可以做到这一点!
React 提供了一种通过使用 React.createRef() 来获取对 DOM 节点的引用的方法。 它实际上只是这个非常熟悉的 JavaScript 片段的等价物:
document.getElementById('foo-id');
这正是 React.createRef() 所做的,尽管它需要一些不同的设置。
用法
要获得对 DOM 节点的引用,您必须做两件事:
import React, { Component } from 'react';
class Foobar extends Component {
constructor(props) {
super(props);
this.myInput = React.createRef(); // initialize "this.myInput"
}
render() {
return (
<input ref={this.myInput}/> {/* pass "this.myInput" as prop */}
);
}
}
React 中的所有标准 HTML 元素都有一个名为 ref 的保留属性(很像 style 是一个保留属性)。 只需将您在构造函数中初始化的 ref 传递给 ref 属性……瞧! 您可以使用 this.myInput.current 开始与 <input> DOM 节点进行交互!
this.myInput.current 持有对 DOM 节点的引用
示例:聚焦
使用最后的代码片段,让我们做一个小调整来演示如何开始与 <input> DOM 节点交互:
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
}
render() {
return (
<div>
<input ref={this.myInput}/>
<button onClick={() => {
this.myInput.current.focus();
}}>
focus!
</button>
</div>
);
}
}
调用 focus() 方法不是 React.js 的事情……这是一个普通的 JavaScript 事情! 💃🏻💃🏻 例如,这是使用 vanilla JavaScript 完成的:
document.getElementById('myInput').focus();
控制 HTML 媒体元素
您还可以使用 React.createRef() 和标准 JavaScript <video> API 来控制播放!
import React, { Component } from 'react';
export default class App extends Component {
constructor(props) {
super(props);
this.myVideo = React.createRef();
}
render() {
return (
<div>
<video ref={this.myVideo} width="320" height="176" controls>
<source src="https://blender.com/big-buck-bunny.mp4" type="video/mp4" />
</video>
<div>
<button onClick={() => {
this.myVideo.current.play();
}}>
Play
</button>
<button onClick={() => {
this.myVideo.current.pause();
}}>
Pause
</button>
</div>
</div>
);
}
}
带有 React Hooks 的 Refs 使用 useRef
React Hooks 中的 Refs 与 class 组件没有太大区别。 它是使用 useRef 钩子实现的。 只要记住省略 this 就可以了🙌
import React, { useRef } from "react";
function App() {
const myInput = useRef(null);
return (
<div>
<input ref={myInput}/>
<button onClick={() => {
myInput.current.focus();
}}>
focus!
</button>
</div>
);
}
你不能使用createRef对于纯功能组件,因为它们缺少许多 React-y 特性,例如状态和生命周期组件
✈️ 有关 createRef() 的详细信息,请访问 React 文档。