一、問題
頁面功能太多,想分成多個自定義組件,結果發現自定義組件樣式不生效。
二、解決辦法(個人推薦第三種)
第一種:外部樣式類
利用 externalClasses
定義段定義若干個外部樣式類實現
鏈接:https://taro-docs.jd.com/taro/docs/component-style.html
/* CustomComp.js */ export default class CustomComp extends Component { static externalClasses = ['my-class'] render () { return <View className="my-class">這段文本的顏色由組件外的 class 決定</View> } } /* MyPage.js */ export default class MyPage extends Component { render () { return <CustomComp my-class="red-text" /> } } /* MyPage.scss */ .red-text { color: red; }
缺點:
1、自定義組件里面的每一個className都需要在externalClasses里面定義,然后才能使用;
2、不能使用 id 選擇器(#a
)、屬性選擇器([a]
)和標簽名選擇器等多種寫法限制;
第二種:使用 CSS Modules(通過引入樣式變量的方式添加className,哪里需要就在哪里引用即可)
鏈接:https://taro-docs.jd.com/taro/docs/css-modules.html
import Taro, { Component } from '@tarojs/taro' import { View, Text } from '@tarojs/components' import styles from './Test.module.scss' export default class Test extends Component { constructor(props) { super(props) this.state = { } } render () { return ( <View className={styles.test}> <Text className={styles.txt}>Hello world!</Text> </View> ) } }
Taro 中內置了 CSS Modules 的支持,但默認是關閉的,如果需要開啟使用,請先在編譯配置中添加如下配置
根目錄下的config/index.js:
// 小程序 mini: { postcss: { // css modules 功能開關與相關配置 cssModules: { enable: true, // 默認為 false,如需使用 css modules 功能,則設為 true config: { namingPattern: 'module', // 轉換模式,取值為 global/module,下文詳細說明 generateScopedName: '[name]__[local]___[hash:base64:5]' } } } }
// h5
h5: { postcss: { // css modules 功能開關與相關配置 cssModules: { enable: true, // 默認為 false,如需使用 css modules 功能,則設為 true config: { namingPattern: 'module', // 轉換模式,取值為 global/module,下文詳細說明 generateScopedName: '[name]__[local]___[hash:base64:5]' } } } }
需要注意文件取名需要在中間加上 .module.
,因為namingPattern配置的'module'模式,只有文件名中包含 .module.
的樣式文件會經過 CSS Modules 轉換處理。
缺點:如果項目中引用了taroUI,發現部分taroUI樣式失效了,而且不能通過樣式覆蓋的方式自定義樣式了。
第三種:全局樣式類
希望組件外樣式類能夠完全影響組件內部,可以將組件構造器中的 options.addGlobalClass
字段置為 true。(只需要在自定義組件添加 static options = {addGlobalClass: true};父頁面的樣式就能作用到自定義組件。)
鏈接:http://taro-docs.jd.com/taro/docs/component-style.html
/* CustomComp.js */ export default class CustomComp extends Component { static options = { addGlobalClass: true } render () { return <View className="red-text">這段文本的顏色由組件外的 class 決定</View> } } /* 組件外的樣式定義 */ .red-text { color: red; }
全局樣式雖然可能造成不同頁面樣式干擾,但只要在最外層起個不一樣命名空間,還是很容易就能避免這種失誤的,相對而言,全局樣式類書寫方便,效果最佳。