这篇文章主要介绍了详解如何在react组件“外”使用父组件的props,现在分享给大家,也给大家做个参考。
在写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( <p classname='styles.app'></p> )}
定制主题是通过初始化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() || {}).setthemesettheme && 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() || {}).getthemeconst custom_theme = gettheme && gettheme()const styles = csjs` .app { background: ${custom_theme.color || theme.color}; }`export default class app extends component { render( <p classname='styles.app'></p> )}
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
在vue中引用 bmob js-sdk(详细教程)
在vue中如何通过v-for处理数组
使用vue如何实现收藏夹
在node.js中有关npm和webpack配置方法
如何通过js将当前时间格式化?
以上就是详细解读在react组件“外”如何使用父组件的详细内容。