reactjs - 如何禁用React的 "Warning: Unknown prop"?

标签 reactjs frontend

我想使用自定义的 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.

React's documentation on DOM Elements

或者您也可以创建自己的自定义组件,该组件返回 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/

相关文章:

reactjs - Reacts/Flux 的存储应该是 GUI 整个状态的快照吗?

reactjs - React Relay 获取列表

javascript - 以声明方式更新组件内的标记

javascript - 观看属性(property)在 Vuejs 中不起作用

reactjs - React Native 中的多选下拉菜单

javascript - 使用 redux 和 React 实现无限滚动

javascript - 将 mask 添加到屏幕中的网络摄像头 View

html - 更改导航栏 Logo 字体

reactjs - 无法调用 useParams 钩子(Hook)

javascript - 应该很简单 : How to preserve data on a page of basic javascript/css/html when going to another page