React 文档提出了两种处理子对父通信的方法。已经提到了第一个,它是将一个或多个函数作为 props 从父组件向下传递通过层次结构,然后在子组件中调用它们。
孩子对父母的沟通:https : //facebook.github.io/react/tips/communicate-between-components.html
二是使用全局事件系统。您可以构建自己的事件系统,该系统可以很容易地用于这些目的。它可能看起来像这样:
var GlobalEventSystem = {
events: {},
subscribe: function(action, fn) {
events[action] = fn;
},
trigger: function(action, args) {
events[action].call(null, args);
}
};
var ParentComponent = React.createClass({
componentDidMount: function() {
GlobalEventSystem.subscribe("childAction", functionToBeCalledWhenChildTriggers);
},
functionToBeCalledWhenChildTriggers: function() {
// Do things
}
)};
var DeeplyNestedChildComponent = React.createClass({
actionThatHappensThatShouldTrigger: function() {
GlobalEventSystem.trigger("childAction");
}
});
这在某种程度上类似于 Flux 模式。使用 Flux 架构可能有助于解决您的问题,因为订阅事件的视图组件的想法是 Flux 的重要组成部分。所以你会让你的父组件订阅你 Store(s) 中的一些事件,这些事件本来是由子组件触发的。