1、父子组件通信
(1)父传子(props 传值)
javascript
// 父组件
function App() {
const name = '张三'
return (
<div className="App">
<Son name={name} />
</div>
);
}
// 子组件
function Son(props) {
return (
<div>{ props.name }</div>
)
}
(2)子传父(回调函数)
javascript
// 父组件
function App() {
const [msg, setMsg] = useState('');
const getMsg = (data) => {
console.log(data)
setMsg(data)
}
return (
<div className="App">
<div>{ msg }</div>
<Son onGetMsg={getMsg} />
</div>
);
}
// 子组件
function Son({ onGetMsg }) {
return (
<div>
<button onClick={() => onGetMsg('子组件给父组件的数据')}>发送数据</button>
</div>
)
}
(3)双向数据绑定
javascript
// 父组件
function App() {
const [msg, setMsg] = useState('');
const getMsg = (data) => {
console.log(data);
setMsg(data)
}
return (
<div className="App">
<div>{ msg }</div>
<Son msg={msg} onGetMsg={getMsg} />
</div>
);
}
// 子组件
function Son({ msg, onGetMsg }) {
return (
<div>
<input type="text" value={msg} onChange={(e) => onGetMsg(e.target.value)} />
</div>
)
}
2、兄弟组件通信
通过状态提升实现兄弟组件之间传值,子传父 => 父传子
javascript
// 父组件
function App() {
const [msg, setMsg] = useState('');
const getMsg = (data) => {
setMsg(data)
}
return (
<div className="App">
this is App
<A onGetMsg={getMsg} />
<B msg={msg} />
</div>
);
}
// 子组件A
function A({ onGetMsg }) {
return (
<div>
this is A component
<button onClick={() => onGetMsg('AAA')}>send</button>
</div>
)
}
// 子组件B
function B(props) {
return (
<div>
this is B component
{ props.msg }
</div>
)
}
3、跨层级组件通信
- 使用createContext创建上下文对象
- 在顶层组件(App)中使用Ctx.Provider组件提供数据
- 在底层组件(B)中通过useContext获取消费数据
javascript
import { createContext, useContext } from 'react';
// 1.使用createContext创建上下文对象
const MsgContent = createContext();
// 父组件
function App() {
const msg = '哈哈哈';
return (
<div className="App">
{/* 2.在顶层组件(App)中使用Ctx.Provider组件提供数据 */}
<MsgContent.Provider value={msg}>
this is App
<A />
</MsgContent.Provider>
</div>
);
}
// 子组件A
function A() {
return (
<div>
this is A component
<B />
</div>
)
}
// 孙子组件B
function B() {
// 3.在底层组件(B)中通过useContext获取消费数据
const msg = useContext(MsgContent);
return (
<div>
this is B component
{msg}
</div>
)
}
4、任意组件通信(Redux/Zustand)
见后续文章