React Typescript-添加自定义属性

时间:2019-02-25 15:40:01

标签: reactjs typescript custom-attributes

React Typescript允许添加自定义data- *属性。 但是是否可以添加自定义属性,例如'name'|| “测试”行为。 ?

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

我加粗了。

  

类型错误:类型'{子代:元素;名称:字符串;数据测试:   串; }'无法分配给type   “ DetailedHTMLProps,HTMLSpanElement>”。   属性“名称”在类型上不存在   “ DetailedHTMLProps,HTMLSpanElement>”。   TS232

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

2 个答案:

答案 0 :(得分:2)

在反应16+时,有可能see

问题是打字稿还不知道

但是您仍然可以添加@ts忽略以进行类型检查

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

答案 1 :(得分:1)

还有另一种方式... 跳过静态检查(打字稿不动态)

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