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

前端之家收集整理的这篇文章主要介绍了如何在React组件“外”使用父组件的Props?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

在写SDK项目的时候碰到一个问题:在直播间初始化SDK时使用默认主题,在专题页初始化SDK时使用其它主题。默认主题在打包时挂在全局环境下供多个页面使用,定制主题需要在初始化SDK的时候传入。

实现起来很简单,判断是否有定制主题,有就使用定制主题,没有就使用默认主题。项目下的基本组件大多是这样的:

  1. import { h,Component } from 'lib/preact'
  2. import csjs from 'lib/csjs'
  3. import { theme } from 'lib/platform'
  4.  
  5. const styles = csjs`
  6. .app {
  7. background: ${theme.color};
  8. }
  9. `
  10.  
  11. export default class App extends Component {
  12. render(
  13. <div className='styles.app'></div>
  14. )
  15. }

定制主题是通过初始化SDK传进来的,子组件可以通过props或者context拿到,但是却不能在class外的styles里面直接使用。

那么如何实现在组件“外”使用父组件的Props呢?如果我们可以把需要使用的Props挂在“全局环境”下,那么不就可以随便使用了吗?

项目结构如下:

  1. .
  2. |——src
  3. | |——lib //公用库
  4. | |——services //抽离出的方法
  5. | |——index.js
  6. | └──App
  7. | └──app.js
  8. └── ...

首先,在services中新建一个customTheme.js文件内容如下:

  1. let value = {}
  2.  
  3. export default () => {
  4.  
  5. const setTheme = (initColor) => {
  6. value = initColor
  7. }
  8.  
  9. const getTheme = () => {
  10. return value
  11. }
  12.  
  13. return {
  14. setTheme,getTheme,}
  15. }

index.js文件中我们可以拿到初始化SDK时传入的定制主题对象,这里我们把这个对象存储到customTheme.js里的value中:

  1. import customTheme from './services/customTheme'
  2.  
  3. ...
  4.  
  5. const setTheme = (customTheme() || {}).setTheme
  6. setTheme && setTheme(customTheme)
  7.  
  8. ...

这样就可以在其它地方直接拿到customTheme的值了

  1. import { h,Component } from 'lib/preact'
  2. import csjs from 'lib/csjs'
  3. import { theme } from 'lib/platform'
  4. import customTheme from '../services/customTheme'
  5.  
  6. const getTheme = (customTheme() || {}).getTheme
  7. const custom_theme = getTheme && getTheme()
  8.  
  9. const styles = csjs`
  10. .app {
  11. background: ${custom_theme.color || theme.color};
  12. }
  13. `
  14.  
  15. export default class App extends Component {
  16. render(
  17. <div className='styles.app'></div>
  18. )
  19. }

哈哈,就是这么简单,分享给跟我一样的菜鸟们。?

原文链接http://codesnote.com/react_pr...

猜你在找的React相关文章