React中的模式是,children属性接受一个函数的模式是什么?

huangapple go评论56阅读模式
英文:

What is the React pattern where the children prop accepts a function?

问题

The React pattern where a component's children prop accepts a function, allowing a component to pass data to arbitrary children, doesn't have a specific widely-recognized name. It's often referred to as "render prop pattern" or "function as children pattern" informally.

As for whether it's a good practice or an anti-pattern, it depends on the use case. This pattern can be quite powerful and flexible for certain scenarios, allowing dynamic rendering and data passing to child components. However, overusing it unnecessarily can make the code less readable. So, it's essential to evaluate its appropriateness on a case-by-case basis.

英文:

I am trying to find the name of the React pattern where a component's children prop accepts a function, allowing a component to pass data to arbitrary children.

Here's an example of this pattern from Formik's docs:

<Formik>
  {({ handleSubmit, handleChange, handleBlur, values, errors }) => (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        onChange={handleChange}
        onBlur={handleBlur}
        value={values.name}
        name="name"
      />
      {errors.name &&
        <div>
          {errors.name}
        </div>}
      <button type="submit">Submit</button>
    </form>
  )}
</Formik>

I tried searching for descriptions of this pattern, but was not able to find anything.

Does this pattern have a name? Are there good uses for it? Is it an anti-pattern?

答案1

得分: 1

这个问题的答案直接在 Formik 文档中(https://formik.org/docs/api/formik#formik-render-methods-and-props)

> <Formik> 是一个帮助你构建表单的组件。它使用了一种由 React Motion 和 React Router 等库推广的渲染 props 模式。

你可以在这里找到更多信息:https://www.patterns.dev/posts/render-props-pattern(寻找"Children as a function")

英文:

The answer to this question is directly in the documentation of Formik (https://formik.org/docs/api/formik#formik-render-methods-and-props)

> <Formik> is a component that helps you with building forms. It uses a render props pattern made popular by libraries like React Motion and React Router.

You can find some more information here: https://www.patterns.dev/posts/render-props-pattern (look for "Children as a function")

huangapple
  • 本文由 发表于 2023年5月26日 00:51:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76334613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定