React 中的无效 DOM 属性“类”警告

React 中的无效 DOM 属性class警告

Invalid DOM property `class` warning in React

要修复 React.js 警告“无效的 DOM 属性class。你的意思是
className”,请使用classNameprop 而不是class在你的标签上。使用
classNameprop 是因为class它是 JavaScript 中的保留字。

无效的 dom 属性类

这是警告如何引起的示例。

应用程序.js
export default function App() { // ⛔️ Warning: Invalid DOM property `class`. Did you mean `className`? return ( <div> <div class="my-class">Some content</div> </div> ); }

代码示例中的问题是我们正在使用
class
prop,但是
class它是 JavaScript 中的保留字。

为了摆脱警告,我们必须使用
className属性而不是class.

应用程序.js
export default function App() { // ✅ Using className return ( <div> <div className="my-class">Some content</div> </div> ); }

The
className
property is not React.js specific, it’s also used in browsers to
programmatically set and get the value of the class attribute of the specified
element.

The reason we have to use className in React is because the class keyword is
a reserved word – it’s used to declare an
ES6 class.

App.js
// 👇️ ES6 class class Person { constructor(name, age) { this.name = name; this.age = age; } } const person = new Person('Alice', 30); console.log(person.name); // 👉️ "Alice"

Another commonly used prop name that may surprise you is – htmlFor. The
htmlFor prop is in label elements instead of for.

App.js
export default function App() { return ( <div> <label htmlFor="firstName">First Name</label> <input id="firstName" type="text" /> </div> ); }

The reason we have to use htmlFor in React is because the for keyword is a
reserved word – it’s used in for loops.