reactjs - Typescript 附加 Prop

标签 reactjs typescript

我正在尝试使用 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.classNameprops.config.placeholder 并且您可以使用其他 Prop ,例如 props.labelprops.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/

相关文章:

angular - 如何构造一个 Angular 库以具有多个导入路径(如 @angular/material),这样做有什么好处?

typescript - 将类型指定为某个字符串文字

javascript - 如何将 html 转换为 draftjs?

javascript - 具有不同路由器的 Bobril 框架

reactjs - 您可能忘记从定义它的文件中导出组件,或者您可能混淆了默认导入和命名导入

javascript - 我可以在编写 TypeScript 单元测试时对依赖项进行猴子补丁吗

node.js - 在 create-react-app 中包含一个共享项目

typescript - 如何在 TypeScript 中严格定义对象值的子类类型

reactjs - Typesafe React 装饰器无法识别传递函数的 ReturnType

javascript - 警告 : Assign object to a variable before exporting as module default