React组件通信-子传父的实现

344 阅读2分钟

这是我参与「第四届青训营 」笔记创作活动的的第9天

为什么要使用组件通信

组件默认情况下只能使用自己的状态。当有的状态需要被跨组件使用时,或者数据需要在组件之间传递时,就不得不用到组件通信。

组件之间有三种关系:

  1. 父子关系
  2. 兄弟关系
  3. 其他关系

而父子关系又有父传子和子传父两种方式,前者简单,后者相对复杂。本文只讲解子传父的实现方式。

子传父

原理

本质上还是父传子的那一套,只不过是父组件向子组件传递回调函数,然后子组件调用该函数,将值传递给父组件。

步骤

  1. 父组件编写回调函数
  2. 将该函数作为子组件属性的值,传给子组件
  3. 子组件通过props接收回调函数
  4. 子组件调用该函数,并将子组件的数据作为参数传递给回调函数
  5. 父组件使用子组件传递过来的值

代码

App为父组件为例,先在父组件中定义回调函数,并把该函数赋值给getSonMsg

getSonMsg = (sonMsg) => {
  console.log(sonMsg)
}

再编写一个子组件Son,从props中获取getSonMsg,并调用这个来自父组件的回调函数

function Son (props) {
  const { getSonMsg } = props
  return (
    <div>this is the son
      <button onClick={() => getSonMsg("来自子组件的数据")}>click</button>
    </div>
  )
}

最后在父组件中渲染一下子组件

render () {
  return (
    <div>
      <Son getSonMsg={this.getSonMsg} />
    </div>
  )
}

即可实现子传父的功能

image.png

完整代码如下:

import React from "react"

function Son (props) {
  const { getSonMsg } = props
  return (
    <div>this is the son
      <button onClick={() => getSonMsg("来自子组件的数据")}>click</button>
    </div>
  )
}

class App extends React.Component {
  // 准备一个函数,传给子组件
  getSonMsg = (sonMsg) => {
    console.log(sonMsg)
  }

  render () {
    return (
      <div>
        <Son getSonMsg={this.getSonMsg} />
      </div>
    )
  }
}

export default App

总结

子传父的实现是建立在父传子的基础上的,它们本质上都是通过在子组件的标签中添加自定义标签,把值传给子组件的props中,然后子组件再取值并处理。只不过子传父很好地体现了React函数式编程的思想,即函数也是一等公民,可以像其他类型数据一样赋值给变量,并通过函数参数传递。