Javascript 警告:未知的 DOM 属性类。你是说 className 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30968113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Warning: Unknown DOM property class. Did you mean className?
提问by jsalonen
I've just started exploring React, by adding a component with a simple render function:
我刚刚开始探索 React,通过添加一个带有简单渲染函数的组件:
render() {
return <div class="myApp"></div>
}
When I run the app, I get the following error:
当我运行该应用程序时,出现以下错误:
Warning: Unknown DOM property class. Did you mean className?
I can solve this by changing class
to className
.
我可以通过更改class
为className
.
The question is; does React enforce this convention? Also why do I need to use className
instead of the conventional class
? If this is a restriction then is it due to JSX syntax or somewhere else?
问题是; React 是否强制执行此约定?另外为什么我需要使用className
而不是传统的class
?如果这是一个限制,那么是由于 JSX 语法还是其他原因?
回答by Viacheslav
Yes, its a React convention:
是的,这是一个 React 约定:
Since JSX is JavaScript, identifiers such as
class
andfor
are discouraged as XML attribute names. Instead, React DOM components expect DOM property names likeclassName
andhtmlFor
, respectively.
由于 JSX 是 JavaScript,不鼓励将诸如
class
和 之for
类的标识符用作 XML 属性名称。相反,阵营DOM组件期望像DOM属性名称className
和htmlFor
分别。
回答by securecurve
Meteor uses babel to transpile ES5 to ES6 (ES2015), so we can deal with it as a normal Node application with babel transpiler added.
Meteor 使用 babel 将 ES5 转译为 ES6(ES2015),因此我们可以将它作为一个普通的 Node 应用程序来处理,并添加了 babel 转译器。
You need to add .babelrc
file to your project's root folder, and add the following items
您需要将.babelrc
文件添加到您项目的根文件夹中,并添加以下项目
{
"plugins": [
"react-html-attrs"
]
}
And of course, you need to install this plugin using npm
:
当然,您需要使用npm
以下命令安装此插件:
npm install --save-dev babel-plugin-react-html-attrs
npm install --save-dev babel-plugin-react-html-attrs
回答by KARTHIKEYAN.A
In React.js there is no for and class properties available so we need to use
在 React.js 中没有 for 和 class 属性可用,所以我们需要使用
for --> htmlFor
class --> className
回答by Nimmi Verma
You can't use class for any HTML tag attribute because JS has another meaning of class. That why you have to use className instead of class.
你不能对任何 HTML 标签属性使用 class,因为 JS 有 class 的另一个含义。这就是为什么你必须使用 className 而不是 class。
And also use htmlFor attribute instead of for.
并且还使用 htmlFor 属性而不是 for。
回答by Muhammad Talha
In HTML we use
在 HTML 中,我们使用
class="navbar"
but in React and ReactNative there is no HTML, we use JSX(Javascript XML) here we use
但是在 React 和 ReactNative 中没有 HTML,我们在这里使用 JSX(Javascript XML)
className="navbar"