React - Context 使用(共享对于一个组件树而言是 “全局” 的数据)
    		       		warning:
    		            这篇文章距离上次修改已过437天,其中的内容可能已经有所变动。
    		        
        		                
                
import React, { useContext } from 'react';
 
// 创建一个React Context对象
const MyContext = React.createContext();
 
// 使用Context.Provider来包裹需要共享数据的组件树
const App = () => (
  <MyContext.Provider value="全局数据">
    <Toolbar />
  </MyContext.Provider>
);
 
// 使用Context.Consumer来消费共享的数据
const Toolbar = () => (
  <div>
    <ThemedButton />
  </div>
);
 
// 使用自定义Hook来简化消费Context数据的过程
const useMyContext = () => useContext(MyContext);
 
// 使用自定义Hook来使用共享的数据
const ThemedButton = () => {
  const contextData = useMyContext();
  return <button>{contextData}</button>;
};这个例子展示了如何在React应用中创建和使用Context来共享全局数据。App组件作为Context的Provider,提供了一个全局的数据,在Toolbar组件中通过ThemedButton组件使用这个数据。useMyContext自定义Hook简化了从Context中获取数据的过程。
评论已关闭