在 React 中,什么是既具有预期的子元素类型又允许它们被包装的好模式?

发布于 2025-01-11 07:40:00 字数 1433 浏览 2 评论 0原文

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你与清晨阳光 2025-01-18 07:40:00

您可以递归地迭代孩子们,

例如使用像 react-itertools

import { map } from "react-itertools";

function Stepper({ children }) {
  //will do a recursive map over all direct and indirect children 
  //instead of a shallow map like React.Children.map
  const statuses = map(
    children,
    (child) => child?.props?.status
  ).filter(s => s !== undefined);

  // Do stuff...
}

这可以让您超越简单的包装器和其他“不可见”元素来找到您期望的子元素,但如果您的用户传递更复杂的结构,这种深度迭代可能会变得昂贵。

如果对库的重大更改是可以接受的,react 文档会提供一些可行的替代模式的建议。例如 render prop

<Stepper 
  statuses={ ['completed', 'started', 'notstarted'] }
  renderStatus={status => <StyledStep status={status}/>)}
/>

You could recursively iterate over the children

e.g. using a library like react-itertools

import { map } from "react-itertools";

function Stepper({ children }) {
  //will do a recursive map over all direct and indirect children 
  //instead of a shallow map like React.Children.map
  const statuses = map(
    children,
    (child) => child?.props?.status
  ).filter(s => s !== undefined);

  // Do stuff...
}

This lets you get past simple wrappers and other "invisible" elements to find the childern you're expecting, but if your users are passing in more complicated structures, this kind of deep iteration could get expensive.

If a breaking change to the library is acceptable, the react docs have some suggestions of alternative patterns that could work. e.g. a render prop

<Stepper 
  statuses={ ['completed', 'started', 'notstarted'] }
  renderStatus={status => <StyledStep status={status}/>)}
/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文