我有3个组成部分:
我希望在Child2上从Child1触发功能(让我们称其为'triggerCallback')。triggerCallback的实现必须在Child2上实现,因为它会突变Child2的变量(我不想由Parent状态管理的变量!)。
import React, { Component } from "react";
const Child1 = props => {
return <button onClick={props.triggerCallback}>Click Me</button>;
};
class Child2 extends Component {
data = [];
shouldComponentUpdate() {
return false;
}
componentWillReceiveProps(receviedProps) {
// here I need to add a prop or a callback notification to fire 'triggerCallback', how?
}
triggerCallback = action => {
console.log("i triggerd from Child1!");
// here mutate data!
};
// componentDidMount() {} and some extra methods.....
render() {
return null;
}
}
const Parent = props => {
// how do i pass function implemnted on Child2 to be called from Child1?
return (
<div>
<Child1 />
<Child2 />
</div>
);
};
预先感谢!
import React, { Component } from "react";
const Child1 = props => {
return <button onClick={props.triggerCallback}>Click Me</button>;
};
class Child2 extends Component {
data = [];
shouldComponentUpdate() {
return false;
}
constructor(props) {
// Feed the function in the setter revieved as props
super(props);
props.getCallBack(this.triggerCallback);
}
triggerCallback = action => {
console.log("i triggerd from Child1!");
// here mutate data!
};
// componentDidMount() {} and some extra methods.....
render() {
return null;
}
}
const Parent = props => {
// Use a state that contains child2's function or an empty callback
const [func, setFunc] = React.useState(() => void(0));
// send setter as props to child2
return (
<div>
<Child1 triggerCallback={func} />
<Child2 getCallBack={(cb) => {setFunc(cb);}} />
</div>
);