1. 安装
npm install pubsub-js
2. 引入
import Pubsub from 'pubsub-js'
3.案例
实现两个兄弟组件可以相互传参,如下图
App.jsx
<>
<Header></Header>
<List></List>
</>
Header.jsx
import React ,{useRef} from "react";
import Pubsub from 'pubsub-js'
export default ()=>{
const ref = useRef(null)
const handleClick = () => {
Pubsub.publish('inputMsg',ref.current.value)
ref.current.value = ''
}
return(
<div>
<input type="text" ref={ref}/>
<button onClick={handleClick}>send msg</button>
</div>
)
}
List.jsx
import React,{useState,useEffect} from "react";
import Pubsub from 'pubsub-js'
export default () => {
const [inputVal,setInputVal] = useState('');
useEffect(()=>{
Pubsub.subscribe('inputMsg',(msg, data)=>{
console.log(msg,data)
setInputVal(data)
})
},[])
return (
<div>
<span>我是订阅的消息:</span>{inputVal}
</div>
)
}