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

小云云
풀어 주다: 2018-01-15 09:12:13
원래의
1575명이 탐색했습니다.

本文主要介绍了详解如何在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( 

) }
로그인 후 복사

定制主题是通过初始化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( 

) }
로그인 후 복사

相关推荐:

使用store来优化React组件

React组件的生命周期函数是什么

React组件之间的通信的实例


위 내용은 如何在React组件“外”使用父组件的Props의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
최신 이슈
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!