React父子组件通信问题

1、传值问题

    1-1父组件向子组件传值

通过props传值

    1-2子组件向父组件传值

首先想父组件可以通过props传值,也可通过props传方法。

父组件通过props向子组件传方法,子组件接受父组件的方法,通过父组件的方法传值并调用,父组件就能接收到子组件的传值了

//父组件

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

    constructor(props) {

        super(props);

        this.state = {

            txt:"我是尼爸爸"

        }

    }

    fn=(data)=>{

        this.setState({

            txt:data

        })

    }

    render() {

        return (

            <div>

                <Child cfn={this.fn}></Child>

                <p>{this.state.txt}</p>

            </div>

        )

    }

}

export default Dad;

//子组件

import React, { Component } from "react";

class Child extends Component {

    constructor(props){

        super(props);

    }

    fn=(data)=>{

        this.props.cfn(data);

    }

    render() {

        return (

          <div>

            //通过事件进行传值

              <button onClick={()=>{this.fn("我是儿子")}}>子组件向父组件传值</button>

          </div>

        )

    }

}

export default Child;

2、相互调用方法(子组件调用父组件的方法,父组件调用子组件的方法)

2-1子组件调用父组件的方法

父组件通过props向子组件传方法,子组件通过this.props.function()直接调用

2-2父组件调用子组件的方法

首先父组件需要获取到子组件的方法,其思路和获取子组件的值一样。

先向子组件传方法,子组件通过父组件传递的方法向父组件传递方法,父组件获取到子组件的方法直接调用。

//父组件

import React, { Component } from "react";

import Child from "./Child";

class Dad extends Component {

    constructor(props) {

        super(props);

        this.state = {

            arr:["暴富","暴瘦"],

            txt:"我是尼爸爸"

        }

    }

    onRef=(ref)=>{

        this.Child=ref;

    }

    click=()=>{

        this.Child.childFn();

    }

    render() {

        return (

            <div>

                <Child onRef={this.onRef}></Child>

                <button onClick={this.click}>父组件调用子组件中的方法</button>

            </div>

        )

    }

}

export default Dad;

//子组件

import React, { Component } from "react";

class Child extends Component {

    constructor(props){

        super(props);

    }

    componentDidMount() {

        this.props.onRef(this)

    }

    childFn=()=>{

        console.log("我是子组件中的方法")

    }

    render() {

        return (

          <div>

          </div>

        )

    }

}

export default Child;

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

推荐阅读更多精彩内容

  • 作为一个合格的开发者,不要只满足于编写了可以运行的代码。而要了解代码背后的工作原理;不要只满足于自己的程序...
    六个周阅读 8,550评论 1 33
  • 40、React 什么是React?React 是一个用于构建用户界面的框架(采用的是MVC模式):集中处理VIE...
    萌妹撒阅读 1,091评论 0 1
  • 目前,react组件有三种写法,分别是es5的createClass写法,es6的class写法,以及statel...
    ZoomFunc阅读 1,872评论 0 1
  • 自己最近的项目是基于react的,于是读了一遍react的文档,做了一些记录(除了REFERENCE部分还没开始读...
    潘逸飞阅读 3,549评论 1 10
  • 前言 开发一个React应用,更多的是在编写组件,而React组件最小的单位就是React元素,编写组件的最大的好...
    itclanCoder阅读 1,202评论 0 1