更新时间:2022-02-07 00:34:43
在父母中定义一个函数并将其发送给child,使用 props
调用子组件中的父函数。类似于:
Define a function in your parent and send it to the child, call the parent function in child component using props
. Something like:
父
class ParentFixturesComponent extends Component {
// don't forget to bind the function in parent
constructor() {
super();
this.state = {
numChildren: 0,
};
this.someFunctionHere = this.someFunctionHere.bind(this);
}
someFunctionHere(param) {
// do whatever you need
}
render() {
const children = [];
for (let i = 0; i < this.state.numChildren; i += 1) {
children.push(<SingleMatchForm key={uuid()}/>)
}
return (
<Fixtures
addMatch={this.onAddMatch.bind(this)}
save={this.onSubmit.bind(this)}
someFunctionHere={this.someFunctionHere}
>
{children}
</Fixtures>
);
}
}
export default ParentFixturesComponent;
儿童
class Fixtures extends Component {
// constructor and other stuff...
childFunctionHere() {
this.props.someFunctionHere(params);
}
render() {
return (
<div id="fixture-parent" onChange={this.childFunctionHere}>
);
}
}
export default Fixtures;