当我在react中使用typescript时,我想跳过每个单独的道具,特别是HTML的本机道具,比如id,name,placeholder等,但我在{...props}上遇到了错误
我已经用InputHTMLAttributes扩展了我的接口,所以typescript不会检查我的道具,但它仍然有未解决的错误
import React, { InputHTMLAttributes } from "react";
import "./styles.css";
interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
nonNativeProp: string;
props: object
}
const MyComponent: React.FC<MyComponentProps> = ({
nonNativeProp,
props
}) => {
return <input type="text" {..props} />;
};
export default function App() {
return (
<div className="App">
<MyComponent
nonNativeProp="abc"
placeholder="Name"
name="something"
id="myInput"
data-custom="custom-attr"
/>
</div>
);
}发布于 2020-05-07 15:12:07
首先,您需要使用rest扩展语法来获得道具,而不是像对象那样进行解构
其次,接口不需要将道具定义为对象
最后,您使用{..props}而不是{...props}。注意道具前的3个点
interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
nonNativeProp: string;
}
const MyComponent: React.FC<MyComponentProps> = ({
nonNativeProp,
...props
}) => {
return <input type="text" {...props} />;
};
export default function App() {
return (
<div className="App">
<MyComponent
nonNativeProp="abc"
placeholder="Name"
name="something"
id="myInput"
data-custom="custom-attr"
/>
</div>
);
}https://stackoverflow.com/questions/61651733
复制相似问题