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

时间:2019-07-13 10:45:00

标签: reactjs typescript redux

我有孩子部分:

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);

问题是:当单击父组件中的按钮时如何调用Child.childFunction()?

我尝试在Child:React.createRef<Ref<Child>>();上创建引用,但收到错误:错误:(13,39)TS2749:'Child'引用一个值,但在此处用作类型。

原因是:子组件中的connect函数。

1 个答案:

答案 0 :(得分:0)

假设您父组件中的函数名为parentFunction

然后在父组件的render方法中,将属性parentFunction赋予子组件,该子组件将引用父组件的功能,例如this.parentFunction

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

在子组件内部,在处理按钮单击的功能上,您将能够访问和调用从父级发送的函数parentFunction,如下所示:

假设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.
};

要详细了解,Passing Data Between React Component