我想使用自定义
h.JSX
声明而不是 global.JSX
,该怎么做?
下面的例子playground会失败,如何让它工作?
TypeScript 文档说将拾取
h.JSX
而不是 global.JSX
,但它不起作用,引用 TS 文档:
如果工厂定义为 React.createElement (默认),编译器将在检查全局 JSX 之前检查 React.JSX。如果工厂定义为 h,它将在全局 JSX 之前检查 h.JSX。
/** @jsx h */
interface ElBuilder {
(tag: any, attrs: Record<string, any> | null, ...content: any[]): any
JSX(tag: any, attrs: Record<string, any> | null, ...content: any[]): any
}
const h: ElBuilder = function(tag, attrs, ...content) {
console.log('h', tag, attrs, content)
}
h.JSX = h
console.log(<div></div>)
// ^Error: JSX element implicitly has type 'any' because no interface 'JSX.IntrinsicElements' exists.ts(7026)
解决方案
/** @jsx h */
export namespace h {
export namespace JSX {
export interface IntrinsicElements {
[tag: string]: any
}
}
}
interface ElBuilder {
(tag: any, attrs: Record<string, any> | null, ...content: any[]): any
}
const h: ElBuilder = function(tag, attrs, ...content) {
console.log('h', tag, attrs, content)
}
console.log(<div></div>)