内置 React API

除了 钩子组件 之外,react 包还导出了一些对定义组件有用的其他 API。此页面列出了所有剩余的现代 React API。

¥In addition to Hooks and Components, the react package exports a few other APIs that are useful for defining components. This page lists all the remaining modern React APIs.


  • createContext 允许你为子组件定义和提供上下文。与 useContext 一起使用

    ¥createContext lets you define and provide context to the child components. Used with useContext.

  • forwardRef 允许你的组件公开一个 DOM 节点作为对父级的引用。与 useRef 一起使用

    ¥forwardRef lets your component expose a DOM node as a ref to the parent. Used with useRef.

  • lazy 允许你推迟加载组件的代码,直到它第一次渲染。

    ¥lazy lets you defer loading a component’s code until it’s rendered for the first time.

  • memo 让你的组件跳过使用相同属性的重新渲染。与 useMemouseCallback 一起使用

    ¥memo lets your component skip re-renders with same props. Used with useMemo and useCallback.

  • startTransition 允许你将状态更新标记为非紧急。类似于 useTransition

    ¥startTransition lets you mark a state update as non-urgent. Similar to useTransition.

  • act 允许你将渲染和交互封装在测试中,以确保在做出断言之前更新已经处理完毕。

    ¥act lets you wrap renders and interactions in tests to ensure updates have processed before making assertions.


资源 API

¥Resource APIs

组件可以访问资源,而无需将它们作为其状态的一部分。例如,组件可以从 Promise 读取消息或从上下文读取样式信息。

¥Resources can be accessed by a component without having them as part of their state. For example, a component can read a message from a Promise or read styling information from a context.

要从资源中读取值,请使用此 API:

¥To read a value from a resource, use this API:

function MessageComponent({ messagePromise }) {
const message = use(messagePromise);
const theme = use(ThemeContext);
// ...
}

React 中文网 - 粤ICP备13048890号