2017-10-28 56 views
6

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

我只是想知道是否仍然使用className而不是类的优点,除了与以前版本的React向后兼容。

回答

5

class是在JavaScript一个关键字和JSX是JavaScript的的延伸。这是React使用className而不是class的主要原因。

在这方面没有任何改变。

3

React文档建议使用cannonical React attribute名称而不是传统的Javascript命名,所以即使React允许将属性传递给DOM,它也会给出警告。

docs:

Known attributes with a different canonical React name: 

    <div tabindex="-1" /> 
    <div class="hi" /> 

React 15: Warns and ignores them. 
React 16: Warns but converts values to strings and passes them through. 
Note: always use the canonical React naming for all supported attributes. 
0

刚刚摆脱多一点光,就已经考虑到其他好的答案的顶部:

你会发现,阵营使用的className代替传统 DOM类。从文档中,“由于JSX是JavaScript, 这样的标识符(如class和for)不鼓励作为XML属性 名称。相反,React DOM组件期望DOM属性名称分别为 className和htmlFor。

http://buildwithreact.com/tutorial/jsx

此外,为了quote zpao(一个阵营贡献者/ Facebook的员工)

我们的DOM组件使用(大部分)的JS API,所以我们选择使用JS 属性(节点.className,而不是node.class)。