首頁  >  文章  >  web前端  >  如何在React元件「外」使用父元件的Props

如何在React元件「外」使用父元件的Props

小云云
小云云原創
2018-01-15 09:12:131597瀏覽

本文主要介紹了詳解如何在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=&#39;styles.app&#39;></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 &#39;./services/customTheme&#39;

...

const setTheme = (customTheme() || {}).setTheme
setTheme && setTheme(customTheme)

...

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


#
import { h, Component } from &#39;lib/preact&#39;
import csjs from &#39;lib/csjs&#39;
import { theme } from &#39;lib/platform&#39;
import customTheme from &#39;../services/customTheme&#39;
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(
    <p className=&#39;styles.app&#39;></p>
  )
}

相關推薦:

使用store來最佳化React元件

React元件的生命週期函數是什麼

React元件之間的通訊的實例


以上是如何在React元件「外」使用父元件的Props的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn