class vs className in React 16

后端 未结 8 2402
感动是毒
感动是毒 2020-11-29 02:56

I saw that React 16 allows for attributes to be passed through to the DOM. So, that means \'class\' can be used instead of className, right?

I\'m just wondering if

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-29 03:59

    class is a keyword in javascript and JSX is an extension of javascript. That's the principal reason why React uses className instead of class.

    Nothing has changed in that regard.

    To expand this a bit more. A keyword means that a token has a special meaning in a language syntax. For example in:

    class MyClass extends React.Class {
    

    Token class denotes that the next token is an identifier and what follows is a class declaration. See Javascript Keywords + Reserved Words.

    The fact that a token is a keyword means that we cannot use it in some expressions, e.g.

    // invalid in older versions on Javascript, valid in modern javascript
    const props = {
      class: 'css class'
    }
    
    // valid in all versions of Javascript
    const props = {
     'class': 'css class'
    };
    
    // invalid!
    var class = 'css';
    
    // valid
    var clazz = 'css';
    
    // invalid!
    props.class = 'css';
    
    // valid
    props['class'] = 'css';
    

    One of the problems is that nobody can know whether some other problem won't arise in the future. Every programming language is still evolving and class can be actually used in some new conflicting syntax.

    No such problems exist with className.

提交回复
热议问题