“id”组件属性不是由组件定义的,但每个组件都应该有它

问题描述 投票:0回答:1

我想实现一个新的 JSX 接口来自定义行为。

我使用以下 tsconfig.json

{
    "compilerOptions": {
        "lib": ["es2015", "dom"],
        "jsx": "react",
        "jsxFactory": "createDOMElement"
    },
    "include": ["./src/**/*"]
}

这是 Main.tsx:

function createDOMElement(tagName: string | Function, props: any, ...children: any[]) {
    if (typeof tagName === 'function') {
        return tagName(props);
    }
    console.log(tagName, props, children);
    return tagName
}

function Button(data: { text: string }) {
    const button = (
        <button>Click me!</button>
    );
    console.log(button);
    return 'OK - from button'
}

export function Main() {
    const el = (
        <Button id="pippo" text="the text" />
    );

    console.log(el)

    return 'OK - from Main'
}

在浏览器中运行时,我在控制台日志中看到:

button null ['Click me!']
Main.tsx:14 button
Main.tsx:23 OK - from button

所以,它按预期工作。 VSCode 对传递给 Button 的“id”不满意。 错误如下:

Type '{ id: string; text: string; }' is not assignable to type '{ text: string; }'.
  Property 'id' does not exist on type '{ text: string; }'.ts(2322)

为什么会出现这种情况?我该如何修复它? 我想允许每个组件都有“id”属性。

typescript jsx
1个回答
0
投票

JSX 是用于 jsx 的全局命名空间。 React 定义了它herehere

要在每个组件中支持

id
,您必须使用密钥扩展
IntrinsicAttributes
接口,如下所示:

declare global {
    namespace JSX {

        interface IntrinsicAttributes {
            id?: string
        }
    }
}

现在,每个组件都可以使用

id
属性进行实例化,即使该组件的签名中没有该属性。

© www.soinside.com 2019 - 2024. All rights reserved.