我有一个 React Wrapper 组件,它接受一些 Prop ,但将所有其他 Prop 转发给子组件(尤其是与 className、id 等原生 Prop 相关的内容)。
但是,当我传递 native Prop 时,Typescript 会提示。查看错误信息:
TS2339: Property 'className' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes< Wrapper > & Readonly< { children?: ReactNode; }> & Readonly< WrapperProps>'.
我怎样才能获得一个具有特定 props 的组件也接受原生 props(不接受任何 props 并放弃类型检查)?
我的代码是这样的:
interface WrapperProps extends JSX.IntrinsicAttributes {
callback?: Function
}
export class Wrapper extends React.Component<WrapperProps>{
render() {
const { callback, children, ...rest } = this.props;
return <div {...rest}>
{children}
</div>;
}
}
export const Test = () => {
return <Wrapper className="test">Hi there</Wrapper>
}
仅供引用:我在这里发现了一个类似的问题,但答案基本上放弃了类型检查,我想避免这种情况:Link to SO-Question
最佳答案
我们可以看看如何div
Prop 定义:
interface IntrinsicElements {
div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}
如果我们使用 React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>
作为基本类型,我们将拥有 div
的所有属性.自 DetailedHTMLProps
只需添加 ref
至 React.HTMLAttributes<HTMLDivElement>
我们可以使用它作为基本接口(interface)来获取所有 div
属性:
interface WrapperProps extends React.HTMLAttributes<HTMLDivElement> {
callback?: Function
}
export class Wrapper extends React.Component<WrapperProps>{
render() {
const { callback, children, ...rest } = this.props;
return <div {...rest}>
{children}
</div>;
}
}
export const Test = () => {
return <Wrapper className="test">Hi there</Wrapper> // works now
}
关于javascript - 在 Typescript React App 中指定特定的 Prop 并接受一般的 HTML Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51835611/