我正在尝试使用子组件中的参数调用父函数,但是我不确定如何使它正常工作。我特别需要能够从另一个函数中的子函数调用父函数,因此我尝试通过prop传递对该函数的引用,但这并不完全正确。父类拥有一个资源,只有它可以通过我传递的特定函数调用与之交互。按照以下方式完成操作后,系统会告诉我该函数未定义。
export class ParentClass extends React.Component {
ParentFunctionWithArguments(a, b) {
alert("a is being used by my private resource");
alert("b is being used by my private resource");
return true; //some result based on a and b
}
render() {
return (
<ChildClass>ParentFunctionWithArguments={() => this.ParentFunctionWithArguments()}</ChildClass>
);
}
}
还有
export class ChildClass extends React.Component {
...
handleOk = (e) => {
...
if (condition) {
if (this.props.ParentFunctionWithArguments(a, b)) {}
}
...
};
...
}
答案 0 :(得分:0)
<childComponent callFromChild={this.parentMethod}/>
//in child component call like below
this.props.callFromChild()
答案 1 :(得分:0)
您只需要将父函数作为子组件的道具,而不是在子组件中调用
export class ParentClass extends React.Component {
ParentFunctionWithArguments(a, b) {
alert("a is being used by my private resource");
alert("b is being used by my private resource");
return true; //some result based on a and b
}
render() {
return (
<ChildClass ParentFunctionWithArguments={this.ParentFunctionWithArguments}></ChildClass>
);
}
}
并简单地像孩子一样称呼它
export class ChildClass extends React.Component {
handleOk = (e) => {
...
if (condition) {
if (this.props.ParentFunctionWithArguments(a, b)) {}
}
...
};
...
}
答案 2 :(得分:0)
我正在寻找的是“绑定”功能
在父级的构造函数中是这样的:
export class ParentClass extends React.component {
constructor() {
this.ParentFunctionWithArguments = this.ParentFunctionWithArguments.bind(this);
}
... //rest unchanged
}
这将允许孩子在香草反应中使用传入的父函数。