1.跨级通讯
创建一个createContext文件 里面导出一个myContext
import { createContext } from "react";
const myContext = createContext()
export default myContext
父组件
import ChilA from "./com/chilA"; // 子组建
import React from "react";
import myContext from './createContext/createContext' // 引入的文件
function App() {
return (
<div className="App">
{/* 传递数据 */}
<myContext.Provider value={200}>
<ChilA/>
</myContext.Provider>
</div>
);
}
export default App;
子组件
import React, { memo } from 'react'
import ChildB from './childB'
const chilA = memo(props => {
return (
<div>
<ChildB/>
</div>
)
})
export default chilA
孙组件
import React, { memo ,useContext} from 'react'
import myContext from '../createContext/createContext'
const childB = memo(() => {
console.log(useContext(myContext))
//在这里得到结果
return (
<div>childB</div>
)
})
export default childB
2.全局通讯
1.下载events npm i events --save
2.新建一个Event文件 里面导出一个构造函数
import {EventEmitter} from 'events'
export default new EventEmitter()
3.父组件
import ChilA from "./com/chilA"; // 子组建
import React from "react";
import mitter from './events/index'
function App() {
return (
<div className="App">
<ChilA/>
<p onClick={e => mitter.emit('call','这是我要穿送的数据')}>123</p>
</div>
);
}
export default App;
子组件
import React, { memo } from 'react'
import ChildB from './childB'
const chilA = memo(props => {
return (
<div>
<ChildB/>
</div>
)
})
export default chilA
孙组件
import React, { memo ,useEffect} from 'react'
import mitter from '../events/index'
const childB = memo(() => {
useEffect(() => {
mitter.addListener('call', msg =>{
console.log(msg)
})
})
return (
<div>childB</div>
)
})
export default childB
页面上点击 123 的时候
得到的数据