React 的组件通信可以分为以下几种:
- 父子组件通信 props / events
- 跨组件通信 useContext hooks
- 兄弟组件通信 events 事件总线
- 全局状态管理redux
1. 父子组件通信
父组件通过传递 props 传递数据给子组件,而子组件通过触发函数(方法)来传递数据给父组件
Parent.jsx
import React, { useState } from 'react'
import Child from './Child'
export default function Parent() {
const [count, setCount] = useState(1)
const [loginInfo, setLoginInfo] = useState({
name: '班尼特',
sword: 'fire',
action: () => {
console.log('班尼特')
},
})
const changeCount = () => {
setCount(() => count + 1)
}
// 绑定在子组件上的方法
const getDataFromParent = (msg) => {
console.log('来自子组件的数据:', msg)
}
return (
<div>
<h2>我是 Parent 组件 {count}</h2>
<button onClick={changeCount}>修改</button>
<Child
info={loginInfo}
getDataFromParent={getDataFromParent}>
<div>
这是 Child 组件中的内容
<h2>这是 Child h2标签中的内容</h2>
</div>
</Child>
</div>
)
}
Child.jsx
import React, { useState } from 'react'
export default function Child({ children, ...rest }) {
/*
在组件的属性中有一个特殊的属性叫children
就是组件标签中间的内容,相当于vue中的slot
...rest相当于 props,表示剩余属性
子组件接收父组件传递过来的属性和方法
*/
const { info, getDataFromParent } = rest
const [msg, setMsg] = useState('我是child 组件')
// const sendDataToParent = () => {
// info.action()
// getDataFromParent(msg)
// }
return (
<div>
<h2>我是Child 组件</h2>
<h2>
{info.name} {info.sword}
</h2>
{/* <button onClick={sendDataToParent}>Click</button> */}
<button
onClick={() => getDataFromParent(msg)}>Click</button>
{/* 展示子组件标签内的内容, 传递 children */}
{children}
</div>
)
}
当然也可以直接传递 props,如果子组件没有嵌套标签的话
import React, { useState } from 'react'
export default function Child(props) {
// 从 props 中结构出传递的属性和方法
const { info, getDataFromParent } = props
const [msg, setMsg] = useState('我是child 组件')
// const sendDataToParent = () => {
// info.action()
// getDataFromParent(msg)
// }
return (
<div>
<h2>我是Child 组件</h2>
<h2>
{info.name} {info.sword}
</h2>
{/* <button onClick={sendDataToParent}>Click</button> */}
<button onClick={() => getDataFromParent(msg)}>Click</button>
</div>
)
}