【问题标题】:Formik pass customized Props to custom Field ComponentFormik 将自定义的 Props 传递给自定义的 Field 组件
【发布时间】:2020-09-07 22:12:43
【问题描述】:

大家晚上好, 我对自定义 Formik 字段有一个小问题..

我正在使用自己的自定义Field,例如:

<Field name="pdfFile" component={FileUpload} />

FileUpload Props 看起来像:

interface FileUploadProps {
    field: FieldInputProps<any>; //These props should probably be derived from Formik
    form: FormikProps<any>;
    width: string;
    height: string;
}

字段和表单已正确传递到组件中,但是如何将宽度和高度传递到组件中?尝试过,但没有成功。

<Field 
    name="pdfFile" 
    component={(props: any) => (
        <FileUpload
            field={props.field}
            form={props.form}
            width={pdfWidth}
            height={pdfHeight}
        />
    )} 
/>  

不幸的是,Formik API 没有提到如何解决这个问题。有没有人遇到过类似的问题并知道如何解决?

非常感谢您的帮助!

【问题讨论】:

    标签: reactjs typescript formik


    【解决方案1】:

    如果您将未在Field 中使用的道具传递给Field,它将被传递给component 道具中的组件。

    所以你可以这样做

    <Field 
        name="pdfFile" 
        width={pdfWidth}
        height={pdfHeight}
        component={FileUpload} 
    /> 
    

    并获取组件props中的值

    const FileUpload = (props) => {
        // props.width
        // props.height
        return ( /* ... */ )
    }
    

    【讨论】:

    • 非常感谢。不知道为什么我不试一试,完美无瑕:)
    猜你喜欢
    • 1970-01-01
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-11-26
    • 2017-07-06
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    相关资源
    最近更新 更多