由于我还不明白的原因,React 不鼓励从父方法调用子方法。然而,他们态度软化,给了我们一个“逃生舱口”,允许我们这样做。你认为“Refs”是逃生舱口的一部分是正确的。如果像我一样,您已经阅读了数十篇搜索此信息的文章,那么您将做好充分准备来了解它们逃生舱口描述 http://facebook.github.io/react/docs/more-about-refs.html
对于您的情况,您可能想在 KpisHeader 类中尝试类似的操作。
改变这一行
<TodayKpi ref="todayKpi" {...this.state}/>
使用像这样的 ref 回调函数:
<TodayKpi ref={(todayKpiComponent) => this.todayKpiComponent = todayKpiComponent} {...this.state}/>
或者,在 ES6 之前,这样:
<TodayKpi
ref=
{
function (todayKpiComponent)
{
this.todayKpiComponent = todayKpiComponent
}
}
{...this.state}
/>
然后,您将能够从 KpisHeader 类访问 TodayKpi 组件方法,如下所示:
this.todayKpiComponent.someMethod();
奇怪的是,对我来说,在 ref 回调函数中,“this”是窗口而不是父组件。所以,我必须添加
var self = this;
在 render 方法上方并在 ref 回调函数中使用“self”。
就我而言,我有未知数量的动态生成的子组件,因此我将每个子组件放入一个数组中。我清除了 componentWillUpdate 中的数组。这一切似乎都有效,但我有一种不安的感觉,尤其是考虑到 React 不喜欢调用子方法。