父传子、孙
Father.js
import React, { useState, createContext } from "react";
import Child from "./Child";
export const CountContext = createContext();
export function Father() {
const [count, setCount] = useState(0);
return (
<div>
<div>我是父组件:{count}</div>
<button onClick={() => { setCount(count + 1) }}>click</button>
<CountContext.Provider value={count}>
<Child />
</CountContext.Provider>
</div>
)
}
export default Father;
Child.js
import React, { useContext } from "react";
import { CountContext } from "./App";
import Sun from "./Sun";
function Child() {
let count = useContext(CountContext);
return (
<div>
<div>我是儿子:{count}</div>
<Sun />
</div>
);
}
export default Child;
Sun.js
import React, {useContext } from "react";
import {CountContext} from "./App"
function Sun() {
let count = useContext(CountContext);
return (
<div>我是孙子:{count}</div>
)
}
export default Sun
孙、子、传父
Father.js
import React, { useState, createContext } from "react";
import Child from "./Child";
export const CountContext = createContext();
export function Father() {
const [count, setCount] = useState(0);
return (
<div>
<div>我是父组件:{count}</div>
<button onClick={() => { setCount(count + 1) }}>click</button>
<CountContext.Provider value = {{ count ,setCount}}>
<Child />
</CountContext.Provider>
</div>
)
}
export default Father;
Child.js
import React, { useContext } from "react";
import { CountContext } from "./App";
import Sun from "./Sun";
function Child() {
let {count ,setCount } = useContext(CountContext);
return (
<div>
<div>我是儿子:{count}</div>
<button onClick={() => { setCount(count + 1) }}>儿子click</button>
<Sun />
</div>
);
}
export default Child;
Sun.js
import React, { useContext } from "react";
import { CountContext } from "./App";
function Sun() {
let { count, setCount } = useContext(CountContext);
return (
<div>
<div>我是孙子:{count}</div>
<button onClick={() => { setCount(count + 1);}}>孙子click</button>
</div>
);
}
export default Sun;