通讯是单向的,数据必须是由一方传到另一方。

1.父组件与子组件间的通信。

在 React 中,父组件可以向子组件通过传 props 的方式,向子组件进行通讯。

父组件 App.js

import React, { Component } from 'react';

import './App.css';

import Child from './child'

class App extends Component {
  constructor(props){
    super(props);
    this.state={
      msg:'父类的消息',
      name:'John',
      age:99
    }
  }

  callback=(msg,name,age)=>{
    // setState方法,修改msg的值,值是由child里面传过来的
    this.setState({msg});
    this.setState({name});
    this.setState({age});
  }

 render() {
  return (
   <div className="App">
    <p> Message:   {this.state.msg}</p>
    <Child callback={this.callback} age={this.state.age} name={this.state.name}></Child>
   </div>
  );
 }
}

export default App;

父组件中,state里面有三个属性,分别是msg,name和age,在子组件child中,如果想拿到父组件里面的属性,就需要通过props传递。

在 <Child></Child> 标签里面添加

name={this.state.name} age={this.state.age}

写成

<Child name={this.state.name} age={this.state.age}></Child>

name和age分别是你要传递的属性。

子组件   Child

import React from "react";

class Child extends React.Component{
  constructor(props){
    super(props);
    this.state={
      name:'Andy',
      age:31,
      msg:"来自子类的消息"
    }
  }

  change=()=>{
    this.props.callback(this.state.msg,this.state.name,this.state.age);
  }

  render(){
    return(
      <div>
        <div>{this.props.name}</div>
        <div>{this.props.age}</div>
        <button onClick={this.change}>点击</button>
      </div>
    )
  }
}

export default Child;

在子组件中,通过 {this.props.name}  {this.props.age}就能拿到父组件里面的数据。

呈现在页面上的就是这个样子。

其中 John,99均来自于父组件App.js

2.子组件向父组件通信

子组件向父组件通讯,同样也需要父组件向子组件传递 props 进行通讯,只是父组件传递的,是作用域为父组件自身的函数,子组件调用该函数,将子组件想要传递的信息,作为参数,传递到父组件的作用域中。

上面例子中,在子组件Child中绑定了onClick事件。 调用this.change方法。

注意change函数采用了箭头函数的写法 change=()=>{},目的是为了改变this的指向。使得在函数单独调用的时候,函数内部的this依然指向child组件

如果不使用箭头函数,而是采用普通的写法

change(){
}

则需要在 constructor中绑定this,

this.change=this.change.bind(this)

或者在onClick方法中绑定this,

onClick={this.change=this.change.bind(this)}

在change方法中,通过props发送出去一个方法,比如说叫callback方法,父组件中去接收这个方法,callback={this.callback},然后在自身的callback函数中进行一些列操作。

本例中,函数callback中就是通过调用 setState方法来改变值。

点击按钮后页面显示:

可以看到,我们既实现了通过props将父组件里面的数据传递给子组件的效果,也实现了通过子组件按钮点击事件,将子组件里面的数据发送给父组件

以上就是【React 父子组件通信的实现方法】的全部内容了,欢迎留言评论进行交流!

赞(0) 踩(0)

与本文相关的软件

发表我的评论

最新评论

  1. 暂无评论