如何向作为props传入的函数式组件传递新定义的props?
解决方案
要给传入的formComponent追加指定props,你可以使用React的React.cloneElementAPI,它能克隆已有的React元素并添加/覆盖props。具体实现步骤如下:
- 确保导入React(如果组件文件未导入):
import React from 'react';
- 修改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
相关产品推荐
相关产品推荐

