之React.createContextを反応させます


インポートは「反応」からリアクト。 「反応-DOM」からインポートReactDOM。 CONST ThemeContext = React.createContext({ 背景:「赤」、 色:「白」 });

静的メソッドによってReact.createContext()作成するContextオブジェクトを、このContextオブジェクトは、2つの成分が含まれ、<Provider />そして<Consumer />

 

クラスのAppはReact.Componentを{拡張します
  {レンダリング()
    リターン <ThemeContext.Provider値= {{背景: 'グリーン'、色: '白'}}>
        <ヘッダー/>
      </ThemeContext.Provider>
    );
  }
}

<Provider />それはvalue現在のと同等getChildContext()

 

クラスヘッダーReact.Componentを{延び
  {レンダリング()
    リターン <タイトル>こんにちはリアクトコンテキストAPI </タイトル>
     );
  }
}
 
クラスタイトルReact.Componentを{延び
  {レンダリング()
    戻り <ThemeContext.Consumer> 
        {コンテキスト =>  <H1スタイル= {{背景:context.background、色:context.color}}> 
            { この.props.childrenは}
           </ H1>
         )}
       </ThemeContext.Consumer >
     );
  }
}

<Consumer />children関数のパラメータによって、利用できる機能である必要があります<Provider />提供しますContext

 

します。https://www.jianshu.com/p/eba2b76b290bからリファレンス

 

おすすめ

転載: www.cnblogs.com/liuw-flexi/p/11652688.html