React不在元素上呈现类 [英] React not rendering classes on elements
问题描述
我目前有两个文件,一个 app.js
和一个 index.html
,当我尝试渲染时一个包含一些CSS类的表单,HTML元素显示但缺少类。
I currently have two files, an app.js
and an index.html
and when I try to render a form with some CSS classes, the HTML elements display but the classes are missing.
这是我的 app.js
:
var Form = React.createClass({
handleClick: function() {
alert('click')
},
render: function() {
return (
<div>
<input class='form-control' type='text' name='list-name'/>
<button class="btn btn-primary" onClick={this.handleClick}>Submit</button>
</div>
);
}
});
ReactDOM.render(<Form/>,document.getElementById('app'));
这是我的HTML正文:
This is my HTML body:
<div class="container">
<h1>Title</h1>
<div id="app" class="center"></div>
</div>
推荐答案
因为 class
可能与ECMAScript冲突(它是一个保留关键字),React开发人员选择使用 className
作为类的HTML元素的属性,而不是类
。根据React文档:
Because class
can conflict with ECMAScript (it's a reserved keyword), React developers chose to use className
as the attribute for HTML elements for classes instead of class
. Per the React documentation:
注意:
因为JSX是JavaScript,所以标识符如class和for不鼓励作为XML属性名称。相反,React DOM组件分别需要DOM属性名称,如className和htmlFor。 来源
由于
和 class
是ECMAScript的保留关键字(其中JavaScript)是一种实现),它们不能用作XML属性名称。这意味着标签的属性,例如 div
或输入
。因此,使用 className
来表示HTML元素的类。以下是一个适用的示例:
Since for
and class
are reserved keywords of ECMAScript (of which JavaScript is an implementation), they cannot be used as XML attribute names. That means attributes of tags such as div
or input
. Thus, use className
to signify an HTML element's class. Here's an applicable example:
return (
<div>
<input className='form-control' type='text' name='list-name'/>
<button className="btn btn-primary" onClick={this.handleClick}>Submit</button>
</div>
);
请注意,使用 className
代替 class
。
这篇关于React不在元素上呈现类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!