createRef
createRef 创建一个 ref 对象,该对象可以包含任意值。
class MyInput extends Component {
inputRef = createRef();
// ...
}参考
🌐 Reference
createRef()
🌐 Call createRef to declare a ref inside a class component.
import { createRef, Component } from 'react';
class MyComponent extends Component {
intervalRef = createRef();
inputRef = createRef();
// ...参数
🌐 Parameters
createRef 不接受任何参数。
返回
🌐 Returns
createRef 返回一个只有单个属性的对象:
current:最初,它被设置为null。你可以稍后将其设置为其他值。如果你将 ref 对象作为ref属性传递给 JSX 节点,React 会设置其current属性。
注意事项
🌐 Caveats
createRef总是返回一个不同的对象。这等同于你自己写{ current: null }。- 在函数组件中,你可能更想使用
useRef,它总是返回相同的对象。 const ref = useRef()等同于const [ref, _] = useState(() => createRef(null))。
用法
🌐 Usage
在类组件中声明引用
🌐 Declaring a ref in a class component
要在class 组件中声明一个 ref,调用 createRef 并将其结果赋值给类字段:
🌐 To declare a ref inside a class component, call createRef and assign its result to a class field:
import { Component, createRef } from 'react';
class Form extends Component {
inputRef = createRef();
// ...
}如果你现在在 JSX 中将 ref={this.inputRef} 传递给 <input>,React 会用输入的 DOM 节点填充 this.inputRef.current。例如,下面是如何创建一个能够聚焦输入框的按钮:
🌐 If you now pass ref={this.inputRef} to an <input> in your JSX, React will populate this.inputRef.current with the input DOM node. For example, here is how you make a button that focuses the input:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
备选方案
🌐 Alternatives
从带有 createRef 的类迁移到带有 useRef 的函数
🌐 Migrating from a class with createRef to a function with useRef
我们建议在新代码中使用函数组件,而不是class组件。如果你有一些使用 createRef 的现有类组件,这里是你可以如何转换它们的方法。以下是原始代码:
🌐 We recommend using function components instead of class components in new code. If you have some existing class components using createRef, here is how you can convert them. This is the original code:
import { Component, createRef } from 'react'; export default class Form extends Component { inputRef = createRef(); handleClick = () => { this.inputRef.current.focus(); } render() { return ( <> <input ref={this.inputRef} /> <button onClick={this.handleClick}> Focus the input </button> </> ); } }
当你将这个组件从类转换为函数时, 将对 createRef 的调用替换为对 useRef 的调用:
🌐 When you convert this component from a class to a function, replace calls to createRef with calls to useRef:
import { useRef } from 'react'; export default function Form() { const inputRef = useRef(null); function handleClick() { inputRef.current.focus(); } return ( <> <input ref={inputRef} /> <button onClick={handleClick}> Focus the input </button> </> ); }