我正在尝试使用 typescript 和 Formik 创建自定义输入字段。我能否获得有关完成下面代码的最佳方法的帮助?我需要添加额外的 Prop 标签和名称...我已经被困在这个问题上有一段时间了,希望我在这里错过了一些很容易的东西!?
{/* {label && <label htmlFor={name} className="text-input-label">{label}</label>} */}
请参阅下面代码中的上述行。
import React from "react";
import styled from "styled-components";
import { FieldHookConfig, useField } from "formik";
interface AdditionalProps {
label: string;
name: string;
}
const MyTextInput = (props: FieldHookConfig<string>) => {
const [field, meta] = useField(props);
return (
<div className={"text-input " + props.className}>
{/* {label && <label htmlFor={name} className="text-input-label">{label}</label>} */}
<div className="card-backdrop">
<input {...field} placeholder={props.placeholder} />
</div>
</div>
);
};
export default styled(MyTextInput)``
谢谢!!!
最佳答案
创建一个新的 prop 作为接口(interface),如下所示,并在组件中将其用作 props 类型
interface ComponentProps<T> {
config : FieldHookConfig<T>;
label: string;
name: string;
}
const MyTextInput = (props: ComponentProps<string>) => {}
因此,您可以在组件中使用 formik 配置(FieldHookConfig),如下所示
props.config.className
或 props.config.placeholder
并且您可以使用其他 Prop ,例如 props.label
和 props.name
最后你的组件看起来像
import React from "react";
import styled from "styled-components";
import { FieldHookConfig, useField } from "formik";
interface ComponentProps<T> {
config : FieldHookConfig<T>;
label: string;
name: string;
}
const MyTextInput = (props: ComponentProps<string>) => {
const [field, meta] = useField(props.config);
return (
<div className={"text-input " + props.config.className}>
{props.label && <label htmlFor={props.name} className="text-input-label">{props.label}</label>}
<div className="card-backdrop">
<input {...field} placeholder={props.config.placeholder} />
</div>
</div>
);
};
export default styled(MyTextInput)
关于reactjs - Typescript 附加 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63784708/