简体   繁体   English

如何在React,TypeScript和Redux中从父组件子函数调用

[英]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? 问题是:当单击父组件中的按钮时如何调用Child.childFunction()?

I have tried to create reference on Child: React.createRef<Ref<Child>>(); 我试图在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. ,但出现错误:错误:(13,39)TS2749:'Child'引用一个值,但在此处被用作类型。

The reason is: connect function in Child component. 原因是:Child组件中的connect函数。

Assuming that the function in your parent component called parentFunction 假设父组件中的函数称为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方法中,将属性parentFunction赋予子组件,该子组件将parentFunction父组件的函数,例如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: 在子组件内部,在处理按钮单击的函数上,您将能够访问和调用从父级发送的函数parentFunction ,如下所示:

supposing that childFunction is the function you handle the button click with: 假设childFunction是处理按钮单击的函数:

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 . 要了解更多信息,请在React Component之间传递数据

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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