createRef
创建 ref 对象 - 访问 DOM 节点或 React 元素 (类组件)
核心概述
createRef 用于创建一个可以附加到 React 元素的 ref 对象。 ref 提供了一种方式来访问 DOM 节点或在 render 方法中创建的 React 元素。
⚠️ 重要:在函数组件中,你应该使用 useRef 而不是 createRef。createRef 主要用于类组件。
类组件 vs 函数组件:类组件使用 createRef, 函数组件使用 useRef。两者的返回值相同,但使用方式不同。
技术规格
TypeScript
function createRef(): RefObject返回一个包含 current 属性的对象,初始值为 null。
TypeScript
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
componentDidMount() {
this.inputRef.current.focus();
}
render() {
return <input ref={this.inputRef} />;
}
}