[英]Do I have to declare placeholder on my reusable input in React with typescript?
I'm creating a React components library with Typescript and have a question.我正在使用 Typescript 创建一个 React 组件库并有一个问题。 Do I have to declare every single input properties in type/interface when creating a reusable component?
创建可重用组件时,我是否必须在类型/接口中声明每个输入属性?
I have an input field created with styled components like this:我有一个使用这样的样式组件创建的输入字段:
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;
I'm trying to use this with placeholder, for example.例如,我正在尝试将其与占位符一起使用。 Typescript throws this error:
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)
As placeholder is intrinsic Input property, I thought it was resolved when I spread props {...rest}
.由于占位符是固有的 Input 属性,我认为当我传播 props
{...rest}
时它已解决。 Input doesn't already knows that placeholder is a string prop?输入还不知道占位符是字符串道具吗? Or onChange is a function, or onFocus?
或者 onChange 是 function,还是 onFocus?
Let me know if this question doesn't make any sense.如果这个问题没有任何意义,请告诉我。
Cheers!干杯!
You have to be explicit when declaring the types.声明类型时必须明确。 Spreading the props
{...rest}
doesn't resolve the types for the custom Input
component.传播道具
{...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>
will include types for all the default attributes that can be passed to a input element. React.HTMLProps<HTMLInputElement>
将包括可以传递给输入元素的所有默认属性的类型。 But if you want the custom Input
component to receive some other custom props as well you have to declare the type for it in the interface.但是,如果您希望自定义
Input
组件也接收一些其他自定义道具,则必须在界面中为其声明类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.