React 组件通信

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>
  )
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值