react父組件調用子組件的方法


1.使用refs來調(react16.3以前的方法)

  首先父組件里調用子組件的地方,給子組件傳個屬性 ref = 'fromFather' ,然后在父組件調用this.refs.fromFather.子組件方法

  

var HelloMessage = React.createClass({
    childMethod: function(){
        alert("組件之間通信成功");
    },
    render: function() {
        return <div> <h1>Hello {this.props.name}</h1>  <button onClick={this.childMethod}>子組件</button></div>
    }
});

// 父組件
var ImDaddyComponent = React.createClass({
    getDS: function(){
        // 調用組件進行通信
        this.refs.getSwordButton.childMethod();
    },
    render: function(){
        return (
                <div>
                    <HelloMessage name="John" ref="getSwordButton" />
                    <button onClick={this.getDS}>父組件</button>
                </div>
        );
    }
});

ReactDOM.render(
        <ImDaddyComponent  />,
        document.getElementById('correspond')
);

2.直接在子組件componentDidMount方法中傳遞自己(react16.3之后)

  在父組件調用子組件的地方,給子組件定義一個屬性,並把自己的方法傳過去,子組件componentDidMount中,使用調用該方法this.props.該方法(this),把子組件自己傳過去.

import React, {Component} from 'react';

export default class Parent extends Component {
    render() {
        return(
            <div>
                <Child onRef={this.onRef} />
                <button onClick={this.click} >click</button>
            </div>
        )
    }

    onRef = (ref) => {
        this.child = ref
    }

    click = (e) => {
        this.child.myName()
    }

}

class Child extends Component {
    componentDidMount(){
        this.props.onRef(this)
    }

    myName = () => alert('xiaohesong')

    render() {
        return ('woqu')
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM