简体   繁体   English

React不在元素上呈现类

[英]React not rendering classes on elements

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.jsindex.html ,当我尝试使用一些CSS类渲染表单时,HTML元素显示但缺少类。

This is my app.js : 这是我的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'));

This is my HTML body: 这是我的HTML正文:

<div class="container">
    <h1>Title</h1>
    <div id="app" class="center"></div>
</div>

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 . 因为class可能与ECMAScript(它是保留关键字)冲突,所以React开发人员选择使用className作为类的HTML元素的属性而不是class Per the React documentation: 根据React文档:

Note : Since JSX is JavaScript, identifiers such as class and for are discouraged as XML attribute names. 注意 :由于JSX是JavaScript,因此不鼓励使用类和for等标识符作为XML属性名称。 Instead, React DOM components expect DOM property names like className and htmlFor, respectively. 相反,React DOM组件分别需要DOM属性名称,如className和htmlFor。 Source 资源

Since for and class are reserved keywords of ECMAScript (of which JavaScript is an implementation), they cannot be used as XML attribute names. 由于forclass是ECMAScript的保留关键字(其中JavaScript是一种实现),因此它们不能用作XML属性名称。 That means attributes of tags such as div or input . 这意味着标签的属性,如divinput Thus, use className to signify an HTML element's class. 因此,使用className表示HTML元素的类。 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>
);

Notice that className is used in place of class . 请注意,使用className代替class

With react you have to use 'className' not class since class is a reserved JavaScript syntax. 有了反应,你必须使用'className'而不是类,因为class是一个保留的JavaScript语法。

Would be like div className="myclass" 就像div className =“myclass”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM