1.ref获取类组件实例
通过 ref 来获取类组件的实例在 React 中非常常见,可以使用 React.createRef() 来创建一个 ref 对象,然后将这个 ref 关联到类组件的实例。以下是一些基本的步骤:
- 创建 ref 对象: 在你的类组件的构造函数中,使用 React.createRef() 创建一个 ref 对象。
- 将 ref 关联到组件: 在 JSX 中,将创建的 ref 对象赋值给组件的 ref 属性。这会将 ref 与组件的实例关联起来。
- 访问组件实例: 通过 ref.current 属性来访问组件的实例。这个属性会在组件挂载后包含对组件实例的引用。
下列代码案例中包含一个父组件 App 和一个子组件 HelloWorld。使用了 createRef() 来创建一个 ref 对象 helloComponentRef,然后将这个 ref 关联到 HelloWorld 组件的实例。
在构造函数中使用 createRef() 创建了一个名为 helloComponentRef 的 ref 对象。在 render() 方法中,你将 HelloWorld 组件的实例与这个 ref 关联起来。还定义了一个方法 getComponent(),它通过 this.helloComponentRef.current 获取了 HelloWorld 组件的实例,并调用了 helloMethod() 方法。
以上这种方式允许在父组件中获取子组件的实例,并调用子组件中的方法,实现了在父组件中与子组件进行交互的目的。
import React, { Component, createRef } from "react";
class HelloWorld extends Component {
helloMethod() {
console.log("执行组件helloMethod方法");
}
render() {
return <div>Hello World</div>;
}
}
export class App extends Component {
constructor() {
super();
this.helloComponentRef = createRef();
}
getComponent() {
console.log("HelloWorld组件实例:", this.helloComponentRef.current);
const hComponent = this.helloComponentRef.current;
hComponent.helloMethod();
}
render() {
return (
<div>
App
<HelloWorld ref={this.helloComponentRef} />
<button onClick={(e) => this.getComponent()}>获取组件实例</button>
</div>
);
}
}
export default App;
案例的执行结果如下
2.ref获取函数组件中的某个DOM元素
2.1 forwardRef
在 React 中,ref 的主要目的是用于引用 DOM 元素或类组件的实例。原始的函数式组件(stateless functional components)不是类,它们不具备实例。因此,在函数式组件中直接使用 ref 是没有意义的,因为没有实例可以引用。
随着 React 版本的演进,React 引入了 forwardRef 这一功能,使得函数式组件也可以接收和传递 ref,这是为了更灵活地处理一些高阶组件或函数式组件的场景。
forwardRef 实际上是一个高阶函数,它接收一个函数组件作为参数,然后返回一个新的函数组件,这个新的函数组件可以接收 ref 属性并将其传递给内部的函数组件。 在函数组件中将 ref 属性向子组件传递。允许访问子组件的 DOM 元素或函数组件的实例。这样,函数式组件就可以在需要时引用 DOM 元素或组件实例。
2.2 案例
下列代码使用了 forwardRef,它允许函数式组件接收 ref 属性并将其传递给内部的 DOM 元素。在 HelloWorld 组件中,将传递的 ref 绑定到了 h2 元素上,这意味着通过 this.helloComponentRef.current 可以引用到 h2元素的 DOM 实例。
代码成功地使用了 forwardRef 来使函数式组件 HelloWorld 能够接收 ref 并将其传递给内部的 DOM 元素,然后在父组件 App 中获取了该函数式组件的实例。
运行结果如下:
import React, { Component, createRef, forwardRef } from "react";
const HelloWorld = forwardRef(function (props, ref) {
return (
<div>
<h2 ref={ref}>HelloWorld函数式组件</h2>
<span>ustb</span>
</div>
);
});
export class App extends Component {
constructor() {
super();
this.helloComponentRef = createRef();
}
getComponent() {
console.log("HelloWorld组件实例:", this.helloComponentRef.current);
}
render() {
return (
<div>
App
<HelloWorld ref={this.helloComponentRef} />
<button onClick={(e) => this.getComponent()}>获取组件实例</button>
</div>
);
}
}
export default App;