引用函数
React 允许你使用 参考文献 获取元素或组件的实例。
¥React allows you to grab the instance of an element or component with refs.
功能组件中的引用
¥Refs in Functional Components
在功能组件内部,可以使用 useRef
钩子访问引用:
¥Inside a functional component, refs are accessed with the useRef
hook:
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}
请注意,useRef
将 ref 值封装在具有 current
属性的对象中。这必须反映在接受 ref 值的任何内容的类型中。
¥Note that useRef
wraps the ref value in an object with a current
property. This must be
reflected in the type of anything accepting the ref value.
类组件中的引用
¥Refs in Class Components
类组件中的引用与函数组件类似。要创建一个属性,请向你的类添加一个属性并将 React.createRef
的结果分配给它。
¥Refs in class components are similar to function components. To create one, add a
property to your class and assign the result of React.createRef
to it.
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}
useRef
和 createRef
之间的一个显着区别是 createRef
不接受默认值。它将用值 null
初始化 ref。这是因为 DOM 元素在第一次渲染 MyComponent
之前不会存在,因此必须使用 null
值。
¥One notable difference between useRef
and createRef
is that createRef
does not accept
a default value. It will initialize the ref with the value null
. This is because
DOM elements will not exist until the first render of MyComponent
and so a null
value
must be used.
再次注意,ref 值封装在具有 current
属性的对象中。
¥Again, note that the ref value is wrapped in an object with a current
property.