【发布时间】:2020-07-04 08:26:32
【问题描述】:
我有 3 个组件:
- 父母
- 孩子1
- Child2 - 不是一个真正的 React 组件(它是一个使用第三个 JavaScript 库的组件,它直接操作 DOM 并且不由 React 管理。 此组件永远不会仅在 componentDidMount 和 componentWillReceiveProps 上呈现和变异)
我希望在 Child2 上从 Child1 触发函数(让我们称她为“triggerCallback”)。 triggerCallback 的实现必须在 Child2 上,因为它会改变 Child2 的 vars(我不想由 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>
);
};
提前致谢!
【问题讨论】:
-
所以将回调从父级传递给子级。当点击孩子时,父母设置一个状态,该状态值被传递给另一个孩子。在另一个孩子获取更新的道具值时,您可以触发方法调用。
标签: javascript reactjs