繁体   English   中英

Typescript 恼人的反应道具警告

[英]Typescript annoying warning on react props

一旦我开始在React中使用Typescript ,我注意到我不喜欢的一件事是需要将每个道具声明给组件。 在此之前我们可以使用{...props}但现在我必须在接口中声明每个原生props ,如refplaceholderdefaultValue等。

interface InputProps {
  customProp: boolean;
  props: any;
}

const Input = ({ customProp, placeholder, ...props }: InputProps) => { 
  //warning 
  return <input type="text" {...props} />;
};

https://codesandbox.io/s/distracted-burnell-vlt3i?file=/src/App.tsx

我想享受只需要在界面中声明非原生道具的旧日子,可能吗? 原生 props 已通过 {...props}

import * as React from "react";
import "./styles.css";

interface InputProps {
  customProp: boolean;
  // props: any; // I think it doesn't need to you.
  [key:string]: any;
}

const Input = ({ customProp, placeholder, ...props }: InputProps) => {
  return <input type="text" {...props} />;
};

export default function App() {
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>

      <Input hello="hello" customProp={false} placeholder={"name"} />
    </div>
  );
}

您可以使用[key:string]: any来享受您的旧时光。

但是,我不想推荐使用[key:string]: any

因为它对typescript没有任何意义。

而且,在我看来,如果您对typescript感到压力,您可以改用js

如果您正在使用 TypeScript,则最佳做法是严格定义每个组件的道具的接口/类型别名。 对于您的Input组件,正确的界面是

interface InputProps {
  customProp: boolean;
  placeholder: string;
  // add other props below
}

话虽如此,接口和类型别名可以被导出、共享和扩展,因此这将减少重复代码的数量。 例如,

interface OtherInputProps extends InputProps {
  value: string;
}

当然,您可以执行[key:string]: any之类的操作,但这完全违背了使用 TypeScript 的目的,因为您实际上忽略了 TypeScript 的类型检查功能。 在这种情况下,t 将不那么冗长,以恢复为 JavaScript。


编辑:刚刚意识到 OP 正在尝试使用其他道具扩展输入道具。 在这种情况下,要使用的正确基类型是 `React.InputHTMLAttributes:

export interface InputProps extends React.InputHTMLAttributes< HTMLInputElement> {
  customProp: boolean;
}

或者

type InputProps = React.InputHTMLAttributes<HTMLInputElement> & {
  customProp: boolean;
}

我想享受只需要在界面中声明非原生道具的旧日子,可能吗?

是的,这是可能的。 Typescript 允许接口从其他接口扩展,因此您可以定义接口以包含输入元素期望的所有内容,以及您的自定义属性:

export interface ExampleProps extends React.HTMLProps<HTMLInputElement> {
  customProp: boolean;
}

const Example: React.FC<ExampleProps> = ({ customProp, placeholder, ...rest }) => {
  const { t } = useTranslation();
  return <input type="text" {...rest} />;
};

有了这个定义,我尝试呈现以下内容是合法的:

const Thing: FC = () => {
  return <Example placeholder="foo" customProp={true} defaultValue="3" />;
};

但是 typescript 会指出,例如,如果我未能传入自定义道具,或者如果我为占位符传入 object。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM