React父子组件通信问题

2020-03-18  本文已影响0人  666同学

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;

上一篇 下一篇

猜你喜欢

热点阅读