W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
在 React 社區(qū)有一個著名的 CSS-in-JS 解決方案: styled-components。但遺憾的是,styled-components
使用 <style>
標簽來動態(tài)地控制樣式,在小程序沒有類似的方案。但我們可以通過 linaria 實現(xiàn)同樣的功能,linaria
主要提供以下特性:
styled-components
的 API使用 linaria
也非常簡單,首先通過 NPM 安裝依賴:
$ npm i linaria
其次配置項目根目錄的 babel.config.js
:
module.exports = {
presets: [
['taro', {
framework: 'react',
ts: true
}],
'linaria/babel' // 添加到 babel-preset
]
}
之后配置 config/index.js
const config = {
mini: {
webpackChain(chain, webpack) {
// linaria/loader 選項詳見 https://github.com/callstack/linaria/blob/master/docs/BUNDLERS_INTEGRATION.md#webpack
chain.module
.rule('script')
.use('linariaLoader')
.loader('linaria/loader')
.options({
sourceMap: process.env.NODE_ENV !== 'production',
})
}
}
}
最后在項目根目錄新建 linaria.config.js
// linaria 配置詳見 https://github.com/callstack/linaria/blob/2eaef3f15b/docs/CONFIGURATION.md#options
module.exports = {
ignore: /node_modules[\/\\](?!@tarojs[\/\\]components)/,
}
在業(yè)務代碼中我們可以這樣使用:
import React from 'react'
import { View } from '@tarojs/components'
import { styled } from 'linaria/react'
const Title = styled(View)`
color: ${props => props.color}
`;
const Index = () => {
return <Title color='red'>
Hello World!
</Title>
}
export default Index
import React from 'react'
import { View } from '@tarojs/components'
import { styled } from 'linaria/react'
const Title = styled(View)<{ color: string }>`
color: ${props => props.color}
`;
const Index: React.FC = () => {
return <Title color='red'>
Hello World!
</Title>
}
export default Index
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: