我想实现一个新的 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”属性。