如何在React/JSX组件中使用Slider Revolution标签并解决类型错误?
解决React TypeScript中自定义HTML元素类型错误的方案
方案1:修正类型声明的位置与写法
你之前将declare namespace JSX写在组件函数内部是无效的,TypeScript无法识别函数作用域内的全局类型声明。
- 方法A:将声明移到组件文件最顶部(函数外部),并使用更严谨的类型替代
any:
declare namespace JSX { interface IntrinsicElements { 'rs-fullwidth-wrap': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> 'rs-module-wrap': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>, HTMLElement> } } export default function Home() { return ( <main className="site-main"> <rs-fullwidth-wrap id="rev_slider_2_1_forcefullwidth" style={{ marginTop: '0px', marginBottom: '0px' }} > {/* 元素内容 */} </rs-fullwidth-wrap> </main> ) }
注:使用HTMLAttributes<HTMLElement>可以让自定义元素继承标准HTML元素的属性(如id、style、className等),比any更规范
- 方法B:创建单独的类型声明文件,比如
src/custom-elements.d.ts,写入:
declare namespace JSX { interface IntrinsicElements { 'rs-fullwidth-wrap': React.HTMLAttributes<HTMLElement> 'rs-module-wrap': React.HTMLAttributes<HTMLElement> } }
然后确保tsconfig.json的include数组包含该文件:
{ "compilerOptions": {}, "include": ["src/**/*", "src/custom-elements.d.ts"] }
方案2:使用类型断言快速跳过检查
如果不想配置全局类型,直接在元素上添加as any断言即可:
export default function Home() { return ( <main className="site-main"> <rs-fullwidth-wrap as any id="rev_slider_2_1_forcefullwidth" style={{ marginTop: '0px', marginBottom: '0px' }} > {/* 元素内容 */} </rs-fullwidth-wrap> </main> ) }
方案3:排查冲突的类型声明
如果项目中存在第三方库的JSX类型声明,可能会覆盖你的自定义声明。可以检查node_modules/@types/react/index.d.ts中的JSX定义,或者将自定义声明放在项目根目录的types文件夹下,在tsconfig.json中配置typeRoots提升优先级:
{ "compilerOptions": { "typeRoots": ["./types", "./node_modules/@types"] } }
内容的提问来源于stack exchange,提问作者János
相关产品推荐
相关产品推荐

