跳至主要内容

Ref 函数

React 允许你使用 refs 获取元素或组件的实例。

函数组件中的 Refs

在函数组件中,使用 useRef hook 访问 refs

1import {useRef} from 'react';2import * as React from 'react';3
4function MyComponent() {5  const buttonRef = useRef<null | HTMLButtonElement>(null);
6 buttonRef as {current: null | HTMLButtonElement}; // useRef wraps the ref value in an object7 return <button ref={buttonRef}>Toggle</button>;8}
5:21-5:58: Cannot call hook [1] because React hooks can only be called within components or hooks. [react-rule-hook]

请注意,useRef 将 ref 值包装在一个具有 current 属性的对象中。这必须反映在接受 ref 值的任何类型的类型中。

类组件中的 Refs

类组件中的 Refs 与函数组件类似。要创建一个,请向你的类添加一个属性,并将 React.createRef 的结果分配给它。

1import * as React from 'react';2
3class MyComponent extends React.Component<{}> {4  // The `null` here is important because you may not always have the instance.5  buttonRef: {current: null | HTMLButtonElement};6
7  constructor() {8    super();9    this.buttonRef = React.createRef<HTMLButtonElement>();10  }11
12  render(): React.Node {13    return <button ref={this.buttonRef}>Toggle</button>;14  }15}

useRefcreateRef 之间的一个显著区别是,createRef 不接受默认值。它将使用值 null 初始化 ref。这是因为 DOM 元素在 MyComponent 的第一次渲染之前不会存在,因此必须使用 null 值。

同样,请注意 ref 值被包装在一个具有 current 属性的对象中。