You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何向作为props传入的函数式组件传递新定义的props?

解决方案

要给传入的formComponent追加指定props,你可以使用React的React.cloneElementAPI,它能克隆已有的React元素并添加/覆盖props。具体实现步骤如下:

  1. 确保导入React(如果组件文件未导入):
import React from 'react';
  1. 修改FormContent组件的Formik回调部分,替换注释区域的代码:
const FormContent = ({
  title,
  formComponent,
}: FormContentPropsType) => (
  <>
    <Formik
      enableReinitialize
      validateOnChange={false}
      initialValues={{
        ...formData,
      }}
      validationSchema={SandboxFormValidationSchema}
      onSubmit={sendForm}
    >
      {({
        values,
        setValues,
        errors,
        setErrors,
        handleSubmit,
      }) => (
        <Form>
          {/* 克隆formComponent并传递需要的props */}
          {React.cloneElement(formComponent, {
            formData: values,
            setFormData: setValues,
            formErrors: errors,
            setFormErrors: setErrors,
            handleSubmit: handleSubmit,
          })}
        </Form>
      )}
    </Formik>
  </>
);

补充说明:

  • React.cloneElement第一个参数是要克隆的React元素(即传入的formComponent),第二个参数是要新增/覆盖的props对象。
  • 原formComponent自带的props会被保留,新传入的同名props会覆盖旧值。
  • 若使用TypeScript,需确保FormContentPropsType中formComponent的类型定义为React.ReactElement,示例:
type FormContentPropsType = {
  title: string;
  formComponent: React.ReactElement;
};

内容的提问来源于stack exchange,提问作者Ellone

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 20:34:58