react中的组件通讯

437 阅读3分钟

前言

今天我们一起看一下react中的组件通讯相关的内容,看一看和vue组件通讯有什么异同呢~


一、组件通讯介绍

1. 特点

独立、可复用、可组合

2. 为什么需要组件通讯?

组件是独立且封闭的单元,默认情况下,只能使用组件自己的数据。 在组件化过程中,我们将一个完整的功能拆分成多个组件。

而在这个过程中,多个组件之间不可避免的要共享某些数据。 为了实现这些功能,就需要打破组件的独立封闭性,让其与外界沟通。 这个过程就是组件通讯。

二、组件通讯方法

1. 基本使用

因为组件有“独立”的特点,所以就会产生组件内和组件外两个概念

组件外向组件内传递数据,是通过组件属性<组件 属性={} />的方式

组件内接收数据,是通过 props 接收(保存)传递进来的数据(函数组件和类组件)

函数组件内通过参数 props 使用传递进来的数据,类组件内通过 this.props 使用传递进来的数据

代码如下(示例):

<Hello name="jack" age={19}/>
funtion Hello(props) {
  console.log(props)
  return (
    <div>接收到数据:{props.name}</div>
  )
}
class Hello extends React.Component {
  render() {
    return (
      <div>接收到的数据:{this.props.age}</div>
    )
  }
}

2. 特点

可以给组件传递任意类型的数据(string,number,array,boolean,object,function,{<p></p>})

props 是只读的对象,只能读取属性的值,无法修改对象

注意:使用类组件时,如果写了构造函数,应该将 props 传递给 super(),否则,无法在构造函数中获取到this.props

代码如下(示例):

class Hello extends React.Component {
  constructor(props) {
    // 推荐将props传递给父类构造函数
    super(props)
  }
  render() {
    return <div>接收到的数据:{this.props.age}</div>
  }
}

三、组件通讯的三种方式

1. 父组件传递数据给子组件

父组件确定要传递给子组件的数据,通常是保存在 state 中的数据 给子组件标签添加属性,值为 state 中的数据 子组件中通过 props 接收父组件中传递的数据

class Parent extends React.Component {
  state = { lastName: '王' }
  render() {
    return (
      <div>
        传递数据给子组件:<Child name={this.state.lastName} />
      </div>
    )
  }
}
function Child(props) {
  return <div>子组件接收到数据:{props.name}</div>
}

2. 子组件传递数据给父组件

思路:利用回调函数,父组件提供回调,子组件调用,将要传递的数据作为回调函数的参数

  • 父组件定义一个回调函数(用于接收数据)
  • 父组件将回调函数作为属性的值,传递给子组件
  • 子组件通过 props 获取到回调函数并调用,回调函数的参数,将作为数据传回到父组件中
class Parent extends React.Component {
  getChildMsg = (msg) => {
    console.log('接收到子组件数据', msg)
  }
  render() {
    return (
      <div>
        子组件:<Child sendMsg={this.getChildMsg} />
      </div>
   )
  }
}
class Child extends React.Component {
  state = { childMsg: 'React’ }
  handleClick = () => {
    this.props.sendMsg(this.state.childMsg)
  }
  return (
    <button onClick={this.handleClick}>
      点我,给父组件传递数据
    </button>
  )
}

3. 兄弟组件

将共享状态提升到最近的公共父组件中,由公共父组件管理这个状态

思想:状态提升 公共父组件职责:1. 提供共享状态 2. 提供操作共享状态的方法

要通讯的子组件只需通过 props 接收状态或操作状态的方法

在这里插入图片描述


总结

Believe in yourself.