简体   繁体   中英

How to call from parent component child function in react, typescript and redux

I have child component:

import * as React from "react";
import {Component} from "react";
import {connect} from "react-redux";

class Child extends Component<any, any> {

    childFunction = () => {
        console.log('childFunction');
    };

    render() {
        return <div>Child</div>
    }
}

export default connect<any, any>(
    null,
    null
)(Child);


and parent component:

import * as React from "react";
import {Component, MouseEvent} from "react";
import {connect} from "react-redux";
import Child from "./Child";

class Parent extends Component<any, any> {

    parentFunction = (e: MouseEvent<HTMLElement>) => {
        console.log("parent");
        //TODO : call child function?
    };

    render() {

        let child = <Child />;

        return <div>
            {child}
            <button onClick={(e) => this.parentFunction(e)}>Call child function from parent</button>

        </div>
    }
}

export default connect<any, any>(
    null,
    null,
    null,
    {forwardRef: true}
)(Parent);

The question is: how to call Child.childFunction() when click on button, which is in Parent component?

I have tried to create reference on Child: React.createRef<Ref<Child>>(); , but get error: Error:(13, 39) TS2749: 'Child' refers to a value, but is being used as a type here.

The reason is: connect function in Child component.

Assuming that the function in your parent component called parentFunction

And in your render method of the parent component, give the property parentFunction to the child component, which will be refering to the parent component's function like this.parentFunction .

render(){
  return (
    <ChildComponent parentFunction={this.parentFunction} />
  )
}

Inside your child component, on the function that handles the button click, you will be able to access and invoke the function parentFunction which is sent from the parent as follows:

supposing that childFunction is the function you handle the button click with:

childFunction = (e) => { //don't forget to include the event to your onclick event handler
  console.log('childFunction');
  this.props.parentFunction(e); //the function invoked after being passed from parent component as a prop.
};

To read more about this, Passing Data Between React Component .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM