我有孩子部分:
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函数。
答案 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.
};