在 React 和 TypeScript 中使用 React.forwardRef 可以让你创建一个组件,该组件能够接收一个 ref 并将其转发给内部的子组件。这对于创建可复用的、支持 ref 的组件非常有用,尤其是在你需要将 ref 传递给受控组件或复合组件的情况下。
示例:使用 React.forwardRef 创建一个可聚焦的按钮
- 创建一个简单的按钮组件首先,我们创建一个简单的按钮组件,它接收一个 ref 并将其转发给内部的 button 元素。
// MyButton.tsx
import React, { forwardRef, ButtonHTMLAttributes } from 'react';
interface MyButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {}
const MyButton = forwardRef<HTMLButtonElement, MyButtonProps>(
(props, ref) => {
return (
<button ref={ref} {...props}>
Click me
</button>
);
}
);
export default MyButton;
解释
我们定义了一个 MyButtonProps 接口,它继承了 ButtonHTMLAttributes。这意味着 MyButton 组件可以接收所有原生按钮元素支持的属性。
我们使用 forwardRef 函数创建组件,并传入一个函数组件作为第一个参数。
函数组件接收两个参数:props 和 ref。
我们通过 ref 属性将 ref 传递给内部的 button 元素。
我们使用 ...props 将其他属性展开并传递给 button 元素。
2. 使用 MyButton 组件接下来,在你的应用中使用 MyButton 组件,并通过 ref 访问它。
// App.tsx
import React, { useRef } from 'react';
import MyButton from './MyButton';
const App: React.FC = () => {
const buttonRef = useRef<HTMLButtonElement>(null);
const handleClick = () => {
console.log('Button was clicked');
};
const focusButton = () => {
if (buttonRef.current) {
buttonRef.current.focus();
}
};
return (
<div>
<h1>React with TypeScript Example</h1>
<MyButton ref={buttonRef} onClick={handleClick} />
<button onClick={focusButton}>Focus the button</button>
</div>
);
};
export default App;
解释
我们创建了一个 ref (buttonRef) 并将其类型设置为 HTMLButtonElement。
我们将 buttonRef 传递给 MyButton 组件。
当点击 "Focus the button" 按钮时,我们通过 buttonRef.current.focus() 来聚焦到 MyButton 组件内部的 button 元素。
总结
创建 Ref:使用 useRef 创建一个 ref。
使用 React.forwardRef:创建一个组件,该组件接收一个 ref 并将其转发给内部的子组件。
传递 Ref:将 ref 传递给你的组件并在需要的地方使用它。