Taro 使用 CSS-in-JS

2021-09-23 21:16 更新

    在 React 社區(qū)有一個著名的 CSS-in-JS 解決方案: styled-components。但遺憾的是,styled-components 使用 <style> 標簽來動態(tài)地控制樣式,在小程序沒有類似的方案。但我們可以通過 linaria 實現(xiàn)同樣的功能,linaria 主要提供以下特性:

    • 近似于 styled-components 的 API
    • 完整的 TypeScript 支持
    • 零運行時

    使用 linaria 也非常簡單,首先通過 NPM 安裝依賴:

    1. $ npm i linaria

    其次配置項目根目錄的 babel.config.js:

    1. module.exports = {
    2. presets: [
    3. ['taro', {
    4. framework: 'react',
    5. ts: true
    6. }],
    7. 'linaria/babel' // 添加到 babel-preset
    8. ]
    9. }

    之后配置 config/index.js

    1. const config = {
    2. mini: {
    3. webpackChain(chain, webpack) {
    4. // linaria/loader 選項詳見 https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md#webpack
    5. chain.module
    6. .rule('script')
    7. .use('linariaLoader')
    8. .loader('linaria/loader')
    9. .options({
    10. sourceMap: process.env.NODE_ENV !== 'production',
    11. })
    12. }
    13. }
    14. }

    最后在項目根目錄新建 linaria.config.js

    1. // linaria 配置詳見 https://github.com/callstack/linaria/blob/2eaef3f15b/docs/CONFIGURATION.md#options
    2. module.exports = {
    3. ignore: /node_modules[\/\\](?!@tarojs[\/\\]components)/,
    4. }

    在業(yè)務代碼中我們可以這樣使用:

    1. import React from 'react'
    2. import { View } from '@tarojs/components'
    3. import { styled } from 'linaria/react'
    4. const Title = styled(View)`
    5. color: ${props => props.color}
    6. `;
    7. const Index = () => {
    8. return <Title color='red'>
    9. Hello World!
    10. </Title>
    11. }
    12. export default Index
    1. import React from 'react'
    2. import { View } from '@tarojs/components'
    3. import { styled } from 'linaria/react'
    4. const Title = styled(View)<{ color: string }>`
    5. color: ${props => props.color}
    6. `;
    7. const Index: React.FC = () => {
    8. return <Title color='red'>
    9. Hello World!
    10. </Title>
    11. }
    12. export default Index


    以上內(nèi)容是否對您有幫助:
    在線筆記
    App下載
    App下載

    掃描二維碼

    下載編程獅App

    公眾號
    微信公眾號

    編程獅公眾號