React 中的无效 DOM 属性class
警告
Invalid DOM property `class` warning in React
要修复 React.js 警告“无效的 DOM 属性class
。你的意思是
className
”,请使用className
prop 而不是class
在你的标签上。使用
className
prop 是因为class
它是 JavaScript 中的保留字。
这是警告如何引起的示例。
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
.
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.
// 👇️ 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
.
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.