【问题标题】:How can i pass render props to children in React functional components?如何将渲染道具传递给 React 功能组件中的子级?
【发布时间】:2021-05-03 10:17:00
【问题描述】:

我正在使用react-final-form 我有一个类似这样的Form 组件:

export function Form = ({ children, onSubmit, initialValues, ...props }) => {
   return (
      <FinalForm 
         initialValues={initialValues} 
         onSubmit={onSubmit}
         render={({ handleSubmit, submitting, pristine, valid }) => (
            <form onSubmit={handleSubmit} className="space-y-6" {...props}>
             {children}
            </form>
         )}
      />
   )
}
export default Form;

我想像这样使用这个表单组件:

<Form>
  ({ valid, pristine, submitting } => (
    <TextInput name="email" label="Email Address" type="email" />
    <Button text="Login" disabled={!valid || pristine || submitting} />
  )
</Form>

我如何将道具 valid、pristine 和 submitting 传递给我的孩子,以便我可以将其用于例如禁用按钮?

【问题讨论】:

    标签: reactjs react-final-form


    【解决方案1】:

    代替

    {children}
    

    试试这个,

    {
        React.Children.map(children, child => {
            if (React.isValidElement(child)) {
                return React.cloneElement(child, { submitting, pristine, valid });
            }
            return child;
        });
    }
    

    【讨论】:

    • 谢谢,但表单组件中没有呈现任何内容。我收到错误消息:Functions are not valid as a React child 我该如何解决这个问题?
    猜你喜欢
    • 2017-02-19
    • 2020-08-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多