React 16 中的类与类名 [英] class vs className in React 16

查看:41
本文介绍了React 16 中的类与类名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到 React 16 允许将属性传递给 DOM.所以,这意味着可以使用 'class' 代替 className,对吗?

我只是想知道除了向后兼容以前版本的 React 之外,仍然使用 className 是否有优势.

解决方案

class 是 javascript 中的关键字,JSX 是 javascript 的扩展.这就是 React 使用 className 而不是 class 的主要原因.

在这方面没有任何改变.

再扩展一点.关键字 表示标记在语言语法中具有特殊含义.例如在:

class MyClass 扩展 React.Class {

Token class 表示下一个标记是一个标识符,接下来是一个类声明.请参阅 Javascript 关键字 + 保留字..>

标记是关键字这一事实意味着我们不能在某些表达式中使用它,例如

//在旧版本的 Javascript 中无效,在现代 javascript 中有效const 道具 = {类:'css类'}//在所有版本的 Javascript 中都有效const 道具 = {'class': 'css 类'};//无效的!var class = 'css';//有效的var clazz = 'css';//无效的!props.class = 'css';//有效的props['class'] = 'css';

问题之一是没有人知道将来是否会出现其他问题.每种编程语言都在不断发展,class 实际上可以用在一些新的冲突语法中.

className 不存在这样的问题.

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 there are advantages to still using className over class, besides being backwards compatible with previous versions of React.

解决方案

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.

这篇关于React 16 中的类与类名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆