React 父子組件方法調用及通信

父=>子

父組件向子組件傳遞數據:通過傳 props 的方式,向子組件進行傳遞數據

父組件調用子組件的方法:可以給子組件,通過ref起個名字,然後在父組件的點擊事件中,通過this.refs.子組件的名字.子組件的方法來實現

子=>父

子組件調用父組件的方法(傳遞參數):通過調用父組件的方法時,通過callback回調傳遞數據。this.props.父組件的方法(傳遞的數據)

父組件 App.js

import React, { Component } from 'react';
import Child from './child'

class App extends Component {
    constructor(props){
        super(props);
        this.state={
            msg:'父類的消息',
            name:'John',
            age:99
        }
    }
    //父組件通過refs調用子組件的方法
    testChildren=()=> {
      this.refs.children.childrenMethod();
    }

    //子組件調用父組件的方法並傳參
    callback2=(msg,name,age)=>{
        // setState方法,修改msg的值,值是由child裏面傳過來的
        this.setState({msg});
        this.setState({name});
        this.setState({age});
    }

  render() {
    return (
      <div>
        <p> Message: &nbsp;&nbsp;{this.state.msg}</p>
        <Child ref="children" callback={this.callback2} age={this.state.age} name={this.state.name}></Child>
        <button onClick={this.testChildren}>父組件調用子組件的方法</button>
      </div>
    );
  }
}

export default App;

nameage分別是父組件傳遞給子組件的屬性。

子組件   Child

import React from "react";

class Child extends React.Component{
    constructor(props){
        super(props);
        this.state={
            name:'Andy',
            age:31,
            msg:"來自子類的消息"
        }
    }
    //父組件調用子組件的方法
    childrenMethod=()=> {
      alert("調用子組件方法");
    }
    //子組件調用父組件的方法
    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}就能拿到父組件裏面的數據。

上面例子中,在子組件Child中綁定了onClick事件。 調用this.change方法。在change方法中,通過props發送出去一個方法,比如說叫callback方法,父組件中去接收這個方法,callback={this.callback2},然後在自身的callback2函數中進行一些列操作。 

 

 

注意change函數採用了箭頭函數的寫法 change=()=>{},目的是爲了改變this的指向。使得在函數單獨調用的時候,函數內部的this依然指向child組件

如果不使用箭頭函數,而是採用普通的寫法
change(){
}

則需要在 constructor中綁定this,
this.change=this.change.bind(this)

或者在onClick方法中綁定this,
onClick={this.change=this.change.bind(this)}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章