![](/img/trans.png)
[英]How to create a reusable Input component with React & TypeScript?
[英]Do I have to declare placeholder on my reusable input in React with typescript?
我正在使用 Typescript 創建一個 React 組件庫並有一個問題。 創建可重用組件時,我是否必須在類型/接口中聲明每個輸入屬性?
我有一個使用這樣的樣式組件創建的輸入字段:
import React from 'react';
import { StyledInput } from './styles';
interface Props {
type?: 'text' | 'password' | 'number' | 'tel' | 'time';
name: string;
}
const Input: React.FC<Props> = ({ type = 'text', name, ...rest }) => {
return <StyledInput type={type} name={name} {...rest} />;
};
export default Input;
例如,我正在嘗試將其與占位符一起使用。 Typescript 拋出此錯誤:
Type '{ name: string; placeholder: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
Property 'placeholder' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.ts(2322)
由於占位符是固有的 Input 屬性,我認為當我傳播 props {...rest}
時它已解決。 輸入還不知道占位符是字符串道具嗎? 或者 onChange 是 function,還是 onFocus?
如果這個問題沒有任何意義,請告訴我。
干杯!
聲明類型時必須明確。 傳播道具{...rest}
不會解析自定義Input
組件的類型。
interface IProps extends React.HTMLProps<HTMLInputElement> {
// type any custom props you want to pass other than-
// existing props for a input like "placeholder", "name" or "type"
}
React.HTMLProps<HTMLInputElement>
將包括可以傳遞給輸入元素的所有默認屬性的類型。 但是,如果您希望自定義Input
組件也接收一些其他自定義道具,則必須在界面中為其聲明類型。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.