我想使用自定义的 prop 进行测试,我将其称为“dataHook”,当使用它时我收到此警告。
示例代码:
<div dataHook="header-title">test me</div>
在运行时我会得到这个:
Warning: Unknown prop `dataHook` on <div> tag. Remove this prop from the element.
in div (created by GBT)
我明白为什么会出现警告,但我知 Prop 体情况,并且这段代码对我来说完全没问题,如何禁用它?
最佳答案
dataHook
不是 div
元素接受的有效属性。如果您想使用 HTML5 data-* 属性,则需要将其连字符:
<div data-hook="header-title">...</div>
In React, all DOM properties and attributes (including event handlers) should be camelCased. For example, the HTML attribute tabindex corresponds to the attribute tabIndex in React. The exception is aria-* and data-* attributes, which should be lowercased.
或者您也可以创建自己的自定义组件,该组件返回 div
元素:
class MyComponent extends React.component {
render() {
const { children, dataHook } = this.props;
// do something with the custom property
return <div>{children}</div>
}
}
...
<MyComponent dataHook="header-title">...</MyComponent>
关于reactjs - 如何禁用React的 "Warning: Unknown prop"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43225087/