案例:现在有个父-子-孙组件 需要进行组件通信
import { useState } from "react";
// 创建上下文
const CountContext = React.createContext();
//子组件
const SonComponent = (props) => {
return (
<div>
<h2>子组件</h2>
<GrandsonComponent></GrandsonComponent>
</div>
);
};
//孙组件
const GrandsonComponent= ({onGetMsg,count}) => {
const msg=count===0?'999':0
return (
<div>
<h3>孙组件</h3>
</div>
);
};
function App() {
const title="hello world";
const [count,setCount]=useState(0);
return (
<div className="App">
<h1>父组件</h1>
<SonComponent/>
</div>
);
}
export default App;
跨组件通信Context
import { useState,useContext ,createContext } from "react";
const CountContext = createContext();
//子组件
const SonComponent = (props) => {
return (
<div>
<h2>子组件</h2>
<GrandsonComponent></GrandsonComponent>
</div>
);
};
//孙组件
const GrandsonComponent = () => {
const { count, setCount ,otherMsg} = useContext(CountContext);
const msg = count === 0 ? '999' : 0;
return (
<div>
<h3>孙组件{count}</h3>
<button onClick={() => setCount(msg)}>{otherMsg}</button>
</div>
);
};
function App() {
const [count,setCount]=useState(0);
const otherMsg='父组件的参数'
return (
<CountContext.Provider value={{ count, setCount,otherMsg }}>
<div className="App">
<h1>父组件 {count}</h1>
<SonComponent />
</div>
</CountContext.Provider>
);
}
export default App;
也是就可以实现跨组件通讯,爷爷传参或方法给孙子,孙子获得参数调用和方法了