React Ref 指南

有时,在使用 React.js 时,您需要一个逃避来写 imperative 类型的代码,直接与 DOM 元素进行交互。

React 提供了通过使用 React.createRef() 来获得 DOM 节点的引用方法. 它实际上只是这个非常熟悉的 JavaScript 片段的对应:

1document.getElementById('foo-id');

這正是「React.createRef()」所做的,儘管它需要稍微不同的設定。

使用

要获得 DOM 节点的引用,你必须做两件事:

 1import React, { Component } from 'react';
 2
 3class Foobar extends Component {
 4  constructor(props) {
 5    super(props);
 6    this.myInput = React.createRef();    // initialize "this.myInput"  
 7  }
 8
 9  render() {
10    return (
11      <input ref={this.myInput}/>        {/* pass "this.myInput" as prop */}
12    );
13  }
14}

React 中的所有标准 HTML 元素都有一个被保留的 prop 名为 ref (类似于 style 是保留的 prop)。 只需将您在 constructor 中初始化的 ref 传送到 ref prop... 然后 voila! 您可以使用 this.myInput.current 开始与 DOM 节点进行交互!

<$>[注] this.myInput.current 包含对 DOM 节点 <$> 的引用


示例:集中一个

拿到最后一个代码片段,让我们做一个小调整来展示我们如何开始与 DOM 节点进行交互:

 1import React, { Component } from 'react';
 2
 3export default class App extends Component {
 4  constructor(props) {
 5    super(props);
 6    this.myInput = React.createRef();  
 7  }
 8  render() {
 9    return (
10      <div>
11        <input ref={this.myInput}/>
12
13        <button onClick={() => {
14          this.myInput.current.focus();
15        }}>
16          focus!
17        </button>
18      </div>
19    );
20  }
21}

称呼focus()方法不是React.js的事情......这是一个正常的JavaScript事情! 🏻 例如,这就是用瓦尼拉JavaScript的方式:

1document.getElementById('myInput').focus();

控制一个HTML媒体元素

您还可以使用React.createRef()和标准的JavaScript<video>API来控制播放!

 1import React, { Component } from 'react';
 2
 3export default class App extends Component {
 4  constructor(props) {
 5    super(props);
 6    this.myVideo = React.createRef();
 7  }
 8  render() {
 9    return (
10      <div>
11        <video ref={this.myVideo} width="320" height="176" controls>
12          <source src="https://blender.com/big-buck-bunny.mp4" type="video/mp4" />
13        </video>
14        <div>
15          <button onClick={() => {
16            this.myVideo.current.play();
17          }}>
18            Play
19          </button>
20          <button onClick={() => {
21            this.myVideo.current.pause();
22          }}>
23            Pause
24          </button>
25        </div>
26      </div>
27    );
28  }
29}

Refs 使用 React Hooks 使用 useRef

Refs 在 React Hooks 中与组件没有太大不同. 它是通过使用 useRef链接实现的。

 1import React, { useRef } from "react";
 2
 3function App() {
 4
 5  const myInput = useRef(null);
 6
 7  return (
 8    <div>
 9      <input ref={myInput}/>
10      <button onClick={() => {
11        myInput.current.focus();
12      }}>
13        focus!
14      </button>
15    </div>
16  );
17}

您不能为纯功能组件使用createRef,因为它们缺乏许多 React-y 功能,如状态和生命周期组件。

✈️ 请访问 React docs 有关 createRef() 的详细信息。

Published At
Categories with 技术
Tagged with
comments powered by Disqus