类式组件
父组件 这样a的子组件就都能接收value
孙组件 这样value就保存再了context中
函数式组件
标准
import React from 'react';
import './App.css';
const numberContext = React.createContext();
function App(){
return (
<numberContext.Provider value={12}>
<div>
<ShowAn />
</div>
</numberContext.Provider>
)
}
function ShowAn(){
return(
<numberContext.Consumer>
{value=><div>the answer is {value}</div>}
</numberContext.Consumer>
)
}
export default App;
使用usecontext
import React,{useContext} from 'react';
import './App.css';
const numberContext = React.createContext();
function App(){
return (
<numberContext.Provider value={520}>
<div>
<ShowAn />
</div>
</numberContext.Provider>
)
}
function ShowAn(){
const value = useContext(numberContext);
return(
<div>
the answer is {value}
</div>
)
}
export default App;
代码转自:https://www.jianshu.com/p/d39a3df09dd5
|