react 父组件调用子组件方法、子组件调用父组件方法,父子组件之间通信

1.父子组件方法调用

// 父组件

import React, {Component} from 'react';

class Parents extends Component {

    constructor(props) {

        super(props);

        this.state = {

        }

    }

    componentDidMount() {

    }


    handleCancel = (e) => {

        console.log('父组件的方法被子组件调用');

    }

    childClick = (e) => {

        this.child.onShow()

    }

    render() {

        return (

           

                { this.child = ref}}>

               

调用子组件的函数

           

        );

    }

}

export default Parents;

// 子组件

import React, {Component} from 'react';

class Child extends Component {

    constructor(props) {

        super(props);

        this.state = {

        }

    }

    componentDidMount() {

        this.props.onRef(this)

    }


    onShow(){

        console.log('子组件的方法被父组件调用')

    }

    render() {

        return (

           

               

{this.props.handleCancel()}}>子组件用this.props调用父组件的函数

           

        );

    }

}

export default Child;


2.父子组件之间传值

transMsg(types){

   var  newOrders=[];

   for(let type of types){

      if(type)

      alert(type);

 }}
this.transMsg(msg) } />

父组件向子组件传值:

this.props.parm;

子组件向父组件传值:子组件通过调用父组件传递到子组件的方法 向父组件传递消息的

this.props.transMsg("hi ~~");

你可能感兴趣的:(react 父组件调用子组件方法、子组件调用父组件方法,父子组件之间通信)