createContext函数创建上下文,useContext函数接收父组件传递过来的数据。
新建一个Example4.js文件,实现父子组件传值:
import React, { useState ,createContext , useContext } from 'react';
const CountContext = createContext();//想共享的要创建上下文
//声明一个子组件,接收count
function Counter(){
let count = useContext(CountContext);
return (
<h2>{count}</h2>
)
}
function Example(){
const [count,setCount] = useState(0);//数组解构
return(
<div>
<p>You clicked {count} times</p>
<button
onClick={()=>{setCount(count+1)}}
>
Click me
</button>
{/* cout被共享出去了 */}
<CountContext.Provider value={count}>
<Counter/>
</CountContext.Provider>
</div>
)
}
export default Example;
实现效果如下,父子组件的count值共享: