欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

详解如何在React组件“外”使用父组件的Props

时间:2021-04-27 09:07:29|栏目:JavaScript代码|点击:

在写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>
  )
}

上一篇:用js来生成随机彩票号码清单

栏    目:JavaScript代码

下一篇:Bootstrap实现渐变顶部固定自适应导航栏

本文标题:详解如何在React组件“外”使用父组件的Props

本文地址:http://www.codeinn.net/misctech/109551.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有