forwardRef的弃用
forwardRef 是一个高阶函数,主要用于让子组件能够接收并转发父组件传递过来的 ref,从而允许父组件直接访问子组件中的 DOM 元素或组件实例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| import React, { useRef, forwardRef } from 'react';
const ChildComponent = forwardRef((props, ref) => { return ( <input ref={ref} type="text" placeholder="请输入内容" /> ); });
const ParentComponent = () => { const inputRef = useRef(null);
const focusInput = () => { inputRef.current.focus(); };
return ( <div> <ChildComponent ref={inputRef} /> <button onClick={focusInput}>聚焦输入框</button> </div> ); };
export default ParentComponent;
|

在最新的 React19中,官网显示 forwardRef 已废弃。
我们无需再用forwardRef 来封装子组件了,直接在子组件中的 props 中接收 ref 即可。

新 API:use

use 是一个 React API,它可以让你读取类似于 Promise
或 context
的资源的值。
他通常搭配 Suspense
组件和错误边界(ErrorBoundary)一起使用
处理 context 的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| import { createContext, use } from 'react';
const ThemeContext = createContext(null);
export default function MyApp() { return ( <ThemeContext value="dark"> <Form /> </ThemeContext> ) }
function Form() { return ( <Panel title="Welcome"> <Button show={true}>Sign up</Button> <Button show={false}>Log in</Button> </Panel> ); }
function Panel({ title, children }) { const theme = use(ThemeContext); const className = 'panel-' + theme; return ( <section className={className}> <h1>{title}</h1> {children} </section> ) }
function Button({ show, children }) { if (show) { const theme = use(ThemeContext); const className = 'button-' + theme; return ( <button className={className}> {children} </button> ); } return false }
|
与 Suspense 、ErrorBoundary 搭配使用的示例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import { use, Suspense } from "react"; import { ErrorBoundary } from "react-error-boundary";
function Message({ messagePromise }) { const messageContent = use(messagePromise); return <p>Here is the message: {messageContent}</p>; }
export function MessageContainer({ messagePromise }) { return ( <ErrorBoundary fallback={<p>⚠️Something went wrong</p>}> <Suspense fallback={<p>⌛Downloading message...</p>}> <Message messagePromise={messagePromise} /> </Suspense> </ErrorBoundary> ); }
|
将调用 use API 的组件包装在错误边界中。如果传递给 use 的 Promise 被拒绝(rejected),将显示错误边界的后备方案。