react hook useContext

在不影响中间组件的情况下, 从根组件向最底层组件传值

根组件使用Provide提供值, 子组件使用useContext获取提供的值

import React, { useState, useContext, useEffect } from "react";
const A = () => {
  return (
    <div>
      A<B></B>
    </div>
  );
};

const B = () => {
  return (
    <div>
      B<C></C>
    </div>
  );
};

const C = () => {
  const age = useContext(AgeContext);
  const score = useContext(ScoreContext);
  return (
    <div>
      C:{age},{score}
    </div>
  );
};

const AgeContext = React.createContext(0);
const ScoreContext = React.createContext(0);

export default () => {
  return (
    <AgeContext.Provider value={18}>
      <ScoreContext.Provider value={60}>
        <A />
      </ScoreContext.Provider>
    </AgeContext.Provider>
  );
};

 

hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » react hook useContext