CSS-in-JS 是一種將 CSS 樣式寫入 JavaScript 檔案內的技術。它允許開發人員使用 JavaScript 語法編寫 CSS 規則,提供更動態和模組化的方法來設計 React 應用程式。隨著基於元件的架構的興起,這種技術越來越受歡迎,其中樣式的範圍僅限於單一元件而不是全域樣式表。
在 React 中,CSS-in-JS 使樣式能夠與其所屬的元件緊密聯繫在一起,確保樣式易於維護和擴展。有幾個流行的函式庫實現了這種技術,例如 Styled Components、Emotion 和 JSS。
作用域樣式:CSS-in-JS 確保樣式作用於各個元件,消除了全域 CSS 衝突的可能性。這使得應用程式更易於維護,因為樣式在其元件內是隔離的。
動態樣式:透過 CSS-in-JS,可以輕鬆使用 JavaScript 變數、道具和狀態來根據元件邏輯動態變更樣式。例如,您可以根據按鈕的狀態變更按鈕的顏色。
基於元件的樣式:樣式與元件邏輯一起編寫,使其更易於管理,尤其是在大型應用程式中。這允許更加模組化和可維護的程式碼庫。
自動供應商前綴:許多 CSS-in-JS 庫,例如 Styled Components 和 Emotion,會自動處理供應商前綴,確保跨瀏覽器相容性。
主題:CSS-in-JS 可以更輕鬆地建立全域主題。您可以在頂層定義配色方案、版式和其他共享樣式,並將它們動態注入到元件中。
樣式化元件 是最受歡迎的 CSS-in-JS 函式庫之一。它允許您在 JavaScript 檔案中編寫實際的 CSS 程式碼,但其範圍僅限於各個元件。
npm install styled-components
import React from 'react'; import styled from 'styled-components'; // Create a styled component const Button = styled.button` background-color: ${(props) => (props.primary ? 'blue' : 'gray')}; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; &:hover { opacity: 0.8; } `; const App = () => { return ( <div> <Button primary>Primary Button</Button> <Button>Secondary Button</Button> </div> ); }; export default App;
Emotion 是另一個受歡迎的 CSS-in-JS 函式庫,它提供了強大的樣式解決方案。它與樣式元件類似,但具有一些附加功能,例如效能最佳化和對伺服器端渲染的更好支援。
npm install @emotion/react @emotion/styled
/** @jsxImportSource @emotion/react */ import { css } from '@emotion/react'; import styled from '@emotion/styled'; const buttonStyle = (primary) => css` background-color: ${primary ? 'blue' : 'gray'}; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; &:hover { opacity: 0.8; } `; const Button = styled.button` ${props => buttonStyle(props.primary)} `; const App = () => { return ( <div> <Button primary>Primary Button</Button> <Button>Secondary Button</Button> </div> ); }; export default App;
JSS 是另一個 CSS-in-JS 函式庫,它允許使用 JavaScript 來寫 CSS。它透過自訂主題和更高級的樣式邏輯等功能提供對樣式的更精細的控制。
npm install jss react-jss
import React from 'react'; import { createUseStyles } from 'react-jss'; const useStyles = createUseStyles({ button: { backgroundColor: (props) => (props.primary ? 'blue' : 'gray'), color: 'white', padding: '10px 20px', border: 'none', borderRadius: '5px', cursor: 'pointer', '&:hover': { opacity: 0.8, }, }, }); const Button = (props) => { const classes = useStyles(props); return <button className={classes.button}>{props.children}</button>; }; const App = () => { return ( <div> <Button primary>Primary Button</Button> <Button>Secondary Button</Button> </div> ); }; export default App;
雖然 CSS-in-JS 有許多優點,但它也面臨一系列挑戰:
CSS-in-JS 是一種設計 React 應用程式的現代方法,它將 JavaScript 和 CSS 的力量結合在一起。透過使用Styled Components、Emotion 或JSS 等函式庫,您可以在JavaScript 檔案中編寫樣式,從而提高程式碼庫的模組化、效能和可維護性。然而,平衡 CSS-in-JS 的使用和潛在的效能考慮非常重要,特別是在大型應用程式中。
以上是CSS-in-JS:React 應用程式的現代樣式的詳細內容。更多資訊請關注PHP中文網其他相關文章!