CSS 的设计受到了 HTML 设计的影响。CSS 在 HTML 诞生时就出现了,并已使用超过 20 年。我们知道,在 React/Vue 等库/框架出现之前,网站被分为 HTML、CSS 和 JavaScript。网站页面没有模块化的概念。每个网站页面都写在单个 HTML/CSS/JavaScript 文件中。 为了提供一种抽象手段来复用样式,CSS 提供了 class 来帮助开发者组合样式并在不同地方复用它们。
1 2 3 4 5 6 7 8 9 10 11 12 13
// Without CSS Class feature <pstyle="color: red; font-weight: bold;">This is a highlighted paragraph.</p> <pstyle="color: red; font-weight: bold;">Another highlighted paragraph.</p>
// Class provide means of abstraction // HTML <pclass="highlight">This is a highlighted paragraph.</p> <pclass="highlight">Another highlighted paragraph.</p> // CSS .highlight { color: red; font-weight: bold; }
React 带来了模块化,使 CSS 类变得多余
React 开始在网站中使用模块化概念,将网站视为页面的组合,而页面是组件的组合。每个组件都有自己的 HTML 结构(JSX)、样式(CSS)和逻辑(JS),可以作为模块复用。
上面的例子在 React 中是这样的:
1 2 3 4 5 6 7 8 9
constHighlightP = ({ children }) => (<pclass="highlight">{children}</p>) // CSS .highlight { color: red; font-weight: bold; } // App <HighlightP>This is a highlighted paragraph.</HighlightP> <HighlightP>Another highlighted paragraph.</HighlightP>