在同一个文件下
申明和使用createContext
下面的Numberdata.Provider中需要包裹着子组件
value={需要传递的值}
const Numberdata = createContext(0);
//下面的Numberdata.Provider中需要包裹着子组件
//value={需要传递的值}
return(
<Numberdata.Provider value={num}>
<Footer />
</Numberdata.Provider>
)
子组件接收、使用参数
接收
const count = useContext(Numberdata)
使用
return(
<div>
{count}
</div>
)
全部代码
import React, { useEffect, useState,useContext,createContext } from "react";
const Numberdata = createContext(0);
const Footer=()=>{
const count = useContext(Numberdata)
return(
<div>
{count}
</div>
)
}
const Home = () => {
const [num, changeNum] = useState(0); //定义一个num 初始值为0 修改方法为changeNum
return (
<div>
<div onClick={() => changeNum((num) => num + 1)}>{num}</div>
<Numberdata.Provider value={num}>
<Footer />
</Numberdata.Provider>
</div>
);
};
export default Home;
不同文件下
传递值的组件
import React, { createContext } from 'react';
export const ColorContext = createContext({})
export const Text = (props:any)=>{
return (
<ColorContext.Provider value={'你爱我我爱你'}>
{props.children}
</ColorContext.Provider>
)
}
接收组件
import React, { useContext } from "react";
import { ColorContext } from "./mider";
const ShowText=()=>{
const Text = useContext(ColorContext)
return(
<div>
{Text}
</div>
)
}
export default ShowText
包裹的住两个的组件
import React from "react";
import ShowText from "./ShowText";
import { Text } from "./mider";
const UesDuc = () => {
return (
<div>
<Text>
<ShowText></ShowText>
</Text>
</div>
);
};
export default UesDuc;