打字稿附加道具

时间:2020-09-07 21:55:16

标签: reactjs typescript

我正在尝试使用打字稿和Formik创建一个自定义输入字段。我能否以最佳方式完成下面的代码,获得一些帮助?我需要添加其他道具标签和名称...我已经坚持了一段时间,希望这里缺少一些非常简单的东西!?

{/* {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)``

谢谢!

2 个答案:

答案 0 :(得分:2)

创建一个新的道具作为界面,如下所示,并将其在组件中用作道具类型

interface ComponentProps<T> {
  config : FieldHookConfig<T>;
  label: string;
  name: string;
}
const MyTextInput = (props: ComponentProps<string>) => {}

因此,您可以在组件中使用formik config(FieldHookConfig),如下所示 props.config.classNameprops.config.placeholder,您可以使用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)

答案 1 :(得分:0)

我找到了一种使用Formiks Field FieldAttributes 组件获得期望结果的方法。

我能够使用所有Formiks内置道具和useField挂钩,并能够传递其他道具以实现对样式的完全控制。

有关我已使用的代码,请参见下文。 :)

import React from "react";
import styled from "styled-components";
import { useField, FieldAttributes, Field } from "formik";

type MyTextInputProps = {
  label?: string;
  name: string;
  className?: string;
} & FieldAttributes<{}>;

const MyTextInput: React.SFC<MyTextInputProps> = ({
  label,
  placeholder,
  type,
  className,
  ...props
}) => {
  const [field, meta] = useField<{}>(props);
  return (
    <div className={"text-input " + className}>
      {label && <label className="text-input-label">{label}</label>}
      <div className="card-backdrop">
        <Field placeholder={placeholder} type={type} {...field} />
        {meta.touched && meta.error && (
          <div className="text-input-error">{meta.error}</div>
        )}
      </div>
    </div>
  );
};

export default styled(MyTextInput)

然后用以下命令调用

<MyTextInput name="displayName" placeholder="Display Name" />
相关问题