gpt4 book ai didi

typescript - 如何在 typescript tsx 代码中扩展 jsx 元素的属性?

转载 作者:搜寻专家 更新时间:2023-10-30 21:19:33 24 4
gpt4 key购买 nike

test.tsx

<img onerror="this.style.display='none'" height="178" cmd="start" />

产量

error TS2339: Property 'onerror' does not exist on type 'HTMLAttributes'.

所以我在 JSX 部分上方的 test.tsx 中添加:

namespace JSX {
interface HTMLAttributes {
onerror?: any; // 1. attempt: add the missing onerror attribute
}
interface IntrinsicElements {
img: any // 2. attempt: generally override the type of img, allowing anything
}
}

但是没有效果。嗯?

如何在本地向我想使用的 JSX 代码添加属性?

我知道我可以粗暴地破解导入的类型文件,但我想知道是否有本地方法。

编辑:除了 onerror 属性(在 preact.d.ts 中“错误地”丢失)之外,我通常还想知道如何将临时属性添加到内部元素甚至我自己的元素中。奇怪的是, typescript 从不提示“data-*”属性,我也可能会切换这些属性(无论如何都想成为一个不错的 html5 开发人员)。但是关于接口(interface) HTMLAttributes 扩展的问题对我来说仍然是开放的。

最佳答案

你需要重新定义react的ImgHTMLAttributes<T>

import * as React from 'react'
declare module 'react' {
interface ImgHTMLAttributes<T> {
onError?: ReactEventHandler<T>;
}
}

或者更好的是在 DOMAttributes 上重新定义它:

import * as React from 'react'
declare module 'react' {
interface DOMAttributes<T> {
onError?: ReactEventHandler<T>;
}
}

编辑

问题涉及 preact,因为它使用 namespace ,我们需要一些三重斜杠才能使事情正常进行:

react.ext.d.ts

/// <reference path="./node_modules/preact/dist/preact.d.ts" />
declare namespace JSX {
interface HTMLAttributes {
onError: JSX.GenericEventHandler;
}
}

test.tsx

/// <reference path="./node_modules/preact/dist/preact.d.ts" />
/// <reference path="react.ext.d.ts" />
import * as React from 'preact'
let x = <img height="178" onError={o => console.log(o)} />;

关于typescript - 如何在 typescript tsx 代码中扩展 jsx 元素的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48450470/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com