React19新特性

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';

// 子组件:使用 forwardRef 转发 ref
const ChildComponent = forwardRef((props, ref) => {
return (
<input
ref={ref}
type="text"
placeholder="请输入内容"
/>
);
});

// 父组件:使用子组件并传递 ref
const ParentComponent = () => {
const inputRef = useRef(null);

const focusInput = () => {
// 通过 ref 直接访问子组件中的 input 元素并调用其方法
inputRef.current.focus();
};

return (
<div>
<ChildComponent ref={inputRef} />
<button onClick={focusInput}>聚焦输入框</button>
</div>
);
};

export default ParentComponent;

forwardRef 已废弃

在最新的 React19中,官网显示 forwardRef 已废弃。

我们无需再用forwardRef 来封装子组件了,直接在子组件中的 props 中接收 ref 即可。

ref 接收

新 API:use

use

use 是一个 React API,它可以让你读取类似于 Promisecontext 的资源的值。

他通常搭配 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),将显示错误边界的后备方案。


React19新特性
https://zouhualu.github.io/20250401/React19新特性/
作者
花鹿
发布于
2025年4月1日
许可协议