在写SDK项目的时候碰到一个问题:在直播间初始化SDK时使用默认主题,在专题页初始化SDK时使用其它主题。默认主题在打包时挂在全局环境下供多个页面使用,定制主题需要在初始化SDK的时候传入。
实现起来很简单,判断是否有定制主题,有就使用定制主题,没有就使用默认主题。项目下的基本组件大多是这样的:
import { h, Component } from 'lib/preact' import csjs from 'lib/csjs' import { theme } from 'lib/platform' const styles = csjs` .app { background: ${theme.color}; } ` export default class App extends Component { render( <div className='styles.app'></div> ) }
定制主题是通过初始化SDK传进来的,子组件可以通过props或者context拿到,但是却不能在class外的styles里面直接使用。
那么如何实现在组件“外”使用父组件的Props呢?如果我们可以把需要使用的Props挂在“全局环境”下,那么不就可以随便使用了吗?
项目结构如下:
. |——src | |——lib //公用库 | |——services //抽离出的方法 | |——index.js | └──App | └──app.js └── ...
首先,在services中新建一个customTheme.js文件,内容如下:
let value = {} export default () => { const setTheme = (initColor) => { value = initColor } const getTheme = () => { return value } return { setTheme, getTheme, } }
在index.js文件中我们可以拿到初始化SDK时传入的定制主题对象,这里我们把这个对象存储到customTheme.js里的value中:
import customTheme from './services/customTheme' ... const setTheme = (customTheme() || {}).setTheme setTheme && setTheme(customTheme) ...
这样就可以在其它地方直接拿到customTheme的值了
import { h, Component } from 'lib/preact' import csjs from 'lib/csjs' import { theme } from 'lib/platform' import customTheme from '../services/customTheme' const getTheme = (customTheme() || {}).getTheme const custom_theme = getTheme && getTheme() const styles = csjs` .app { background: ${custom_theme.color || theme.color}; } ` export default class App extends Component { render( <div className='styles.app'></div> ) }
哈哈,就是这么简单,分享给跟我一样的菜鸟们,以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 王子异《1996 Part.2》[320K/MP3][18.29MB]
- 群星.1994-宝丽金最倾情3CD【宝丽金】【WAV+CUE】
- 乐俊亨.2024-同泪【CharioticMusic】【FLAC分轨】
- 何耀珊.2006-收获【华纳】【WAV+CUE】
- 梁汉文1994-壹精选[华星][WAV+CUE]
- 洪荣宏1981-歹路不可行·相思雨(飞跃复刻版)[光美][WAV+CUE]
- 旅行团2015-10Day’s[来福胶泥][WAV+CUE]
- 龙千玉.2011-卡将哟【豪记】【WAV+CUE】
- 蔣志光.1993-多情多寂寞(国专)【BMG】【WAV+CUE】
- 陈慧娴.1996-雪映美白96演唱会2CD(2024环球红馆40复刻系列)【环球】【WAV+CUE】
- 王子异《1996 Part.2》[FLAC/分轨][50.66MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[320K/MP3][155.91MB]
- 贵族音乐《古典名曲与轻音乐钢琴 打开宝宝睡眠开关》[FLAC/分轨][251.78MB]
- 黄韵玲2001-巴结音乐[全员集合][WAV+CUE]
- 郑绪岚2015-流金岁月·精选[首版][WAV+CUE]