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 (

            <section>

                <Child onCancel={this.handleCancel} onRef={(ref)=>{ this.child = ref}}></Child>

                <div onClick={this.childClick}>调用子组件的函数</div>

            </section>

        );

    }

}

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 (

            <section>

                <div onClick={()=>{this.props.handleCancel()}}>子组件用this.props调用父组件的函数</div>

            </section>

        );

    }

}

export default Child;


2.父子组件之间传值

transMsg(types){

   var  newOrders=[];

   for(let type of types){

      if(type)

      alert(type);

 }}
<Child parm={ this.state.msg}  transMsg={ msg => this.transMsg(msg) } />

父组件向子组件传值:

this.props.parm;

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

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

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,040评论 0 1
  • 很感谢https://segmentfault.com/u/cwl提供的答案React 组件间通讯 说 React...
    喵呜Yuri阅读 923评论 0 2
  • 3. JSX JSX是对JavaScript语言的一个扩展语法, 用于生产React“元素”,建议在描述UI的时候...
    pixels阅读 2,878评论 0 24
  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,508评论 1 33
  • qqq1.集众所思,一条建议换一节私教体验课? 2.培训?细节化!洗手液,新器械? 3.积分成就系统: 通过...
    我是林瓜瓜阅读 586评论 0 0