2017-10-28 30 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)。