🎶 Sym - 一款用 Java 实现的现代化社区(论坛/BBS/社交网络/博客)平台

📕 思源笔记 - 一款桌面端笔记应用,支持 Windows、Mac 和 Linux

🎸 Solo - B3log 分布式社区的博客端节点,欢迎加入下一代社区网络

♏ Vditor - 一款浏览器端的 Markdown 编辑器

为什么 React 要使用 className 来代替 HTML 中的 class?

2019-03-03

回答

React 一开始的理念是想与浏览器的 DOM API 保持一直而不是 HTML,因为这样会和元素的创建更为接近。在元素上设置 class 需要使用 className 这个 API:

const element = document.createElement("div")
element.className = "hello" 

加分回答

  • ES5 之前,在对象中不能使用保留字。以下代码在 IE8 中将会抛出错误:
const element = {
  attributes: {
    class: "hello"
  }
} 
  • 在现代浏览器环境中,如果尝试为其分配一个变量时解构时就会抛出错误:
const { class } = { class: 'foo' } // Uncaught SyntaxError: Unexpected token }
const { className } = { className: 'foo' } 
const { class: className } = { class: 'foo' } 
  • 使用 class 做为属性并不会出现问题,就像其他库一样,比如 Preact。React 在 16.3 中允许使用 class,但是会抛出一个警告并将其转换为 className。但经过 2019 年 1 月的开放讨论后,在 16.8 中使用 class 将直接抛出错误 Property 'class' does not exist on type

返回总目录

30 秒面试系列一


欢迎注册黑客派社区,开启你的博客之旅。让学习和分享成为一种习惯!

留下你的脚步