React Typescript - Adding custom attribute

馋奶兔 提交于 2019-12-11 06:45:00

问题


React Typescript allow to add custom data-* attributes. But is it possible to add custom attributes like 'name' || 'test' act. ?

<span name="I'm causing a type error" data-test="I'm Working"/>

Bold added by me.

type error: Type '{ children: Element; name: string; data-test: string; }' is not assignable to type 'DetailedHTMLProps, HTMLSpanElement>'. Property 'name' does not exist on type 'DetailedHTMLProps, HTMLSpanElement>'. TS232

"react": "^16.7.0",
"typescript": "^3.2.4",

回答1:


in react 16+ it is possible, see

probem is that typescript didnt know about it(yet)

but you can still add @ts ignore for typechecking

{ //@ts-ignore
  <span name="I'm causing a type error" data-test="I'm Working"/>
}



回答2:


there is another way... skipping the static check (typescript don't do dynamic)

{ 
  const allowedProps = {test: "not-data-attribute"}
  <span {...allowedProps}/>
}


来源:https://stackoverflow.com/questions/54869777/react-typescript-adding-custom-attribute

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!