前言

这节咱们将介绍 React 中父子组件通信的办法,父与子通信、子与父通信的办法。

本文会向你介绍以下内容:

  • 初识组件的嵌套
  • 父组件向子组件通信
  • 子组件向父组件通信

初识组件的嵌套

让咱们回顾一下在之前的学习中,咱们说过:

组件容许你将 UI 拆分为独立可复用的代码片段,并对每个片段进行独立构思

为什么要进行组件嵌套呢?

如果一个应用程序的所有逻辑全存在于一个组件中,那这个组件会变的相当臃肿且让保护人员望而生畏。

所以咱们通常是组件化开发,而组件化开发的核心思想便在于将一个大组件拆分成许多小组件,而后再将这些组件组合嵌套在一起,造成咱们的应用程序。

剖析一下上面代码的嵌套逻辑

class App extends React.Component {  render(){    return (        <div>          <Comment />          <Avatar  />      </div>    )  }}function Comment (){  return(    <div>评论:你真难看</div>  )}function Avatar (){  return(      <img src=""></img>    <div>小明</div>  )}

层级是这样的

当组件仅用来展现时,这对咱们开发者来说是相当敌对了,可组件要互相进行通信呢?

  • 比方 App 中进行了网络申请获取了数据,当初要将数据传递上来,让 Comment 组件拿到相应数据进行渲染
  • 也可能是子组件中产生了某些事件,须要由父组件来实现某些操作,那就须要子组件向父组件传递事件

来了,来了,本章的主题来了!

父组件向子组件通信

当子组件为 Class 组件

class App extends React.Component {  render(){    return (        <div>          <Comment comment='评论:你真难看!'/>          <Avatar  src='https://xhs-rookies.com/' name='小明'/>      </div>    )  }}class Comment extends React.Component {  constructor(props){    super(props);  }  return(    <div>{this.props.comment}</div>  )}class Avatar extends React.Component {  constructor(props){    super(props);  }  return(      <img src={this.props.src}></img>    <div>{this.props.name}</div>  )}
留神:props 的次要作用是让应用该组件的父组件能够传入参数来配置该组件。它是内部传进来的配置参数,组件外部无法控制也无奈批改。除非内部组件被动传入新的 props,否则组件的 props 永远放弃不变。

所有 React 组件都必须像纯函数一样爱护它们的 props 不被更改。

当子组件为 function 组件

当咱们的组件为 function 时又是怎么的呢?

class App extends React.Component {  render(){    return (        <div>          <Comment comment='评论:你真难看!'/>          <Avatar  src='https://xhs-rookies.com/' name='小明'/>      </div>    )  }}function Comment (props){    const {comment} = props;  return(    <div>{comment}</div>  )}function Avatar (props){    const {src , name} = props;  return(      <img src={src}></img>    <div>{name}</div>  )}

function 组件相对来说比较简单,因为不须要有构造方法,也不须要有 this 的问题。

子组件向父组件通信

某些状况下,咱们须要从子组件向父组件传递音讯。

React 中同样是通过 props 传递音讯,只是此时由父组件传递给子组件一个回调函数,在子组件中调用此函数即可。

让咱们看看怎么实现这个需要呢?

  • Comment 组件中有点赞按钮
  • 当点击点赞按钮时,评论组件中需显示点赞数+1
class Comment extends React.Component {  constructor(props){    super(props);    this.state = {      counter:0    }  }  changeCoutenr(count){    this.setState({      counter: this.state.counter + count    })  }  return(    <div>         <div>{this.props.comment}</div>             <p>{'以后点赞数'+this.state.counter}      <thumsButton btnClick={e => this.changeCounter(1)}></thumsButton>    </div>  )}function thumsButton (props){  const {btnClick} = props;  return <button onClick={btnClick}>点赞</button>}

下节预报

在这一节咱们学习了React中父子组件通信,在下一节中,咱们将给大家介绍React中非父子组件通信的性能常识,敬请期待!