React:无法调用子组件内的函数
发布时间:2020-12-15 05:07:55 所属栏目:百科 来源:网络整理
导读:我试图通过this.refs调用子组件内的函数,但我不断收到此函数不存在的错误. Uncaught TypeError: this.refs.todayKpi.loadTodaysKpi is not a function 父组件: class KpisHeader extends React.Component { constructor() { super(); this.onUpdate = this.
我试图通过this.refs调用子组件内的函数,但我不断收到此函数不存在的错误.
Uncaught TypeError: this.refs.todayKpi.loadTodaysKpi is not a function 父组件: class KpisHeader extends React.Component { constructor() { super(); this.onUpdate = this.onUpdate.bind(this); } render(){ return <div> <DateRange ref="dateRange" onUpdate={this.onUpdate}/> <TodayKpi ref="todayKpi" {...this.state}/> </div>; } onUpdate(val){ this.setState({ startDate: val.startDate,endDate: val.endDate },function(){ this.refs.todayKpi.loadTodaysKpi(); }); } } 我想通过函数onUpdate从DateRange组件中获取一些数据,然后我想在TodayKpi中触发一个从服务器获取数据的函数.现在它只是console.log(“AAA”);. 子组件: class TodayKpi extends React.Component { constructor() { super(); this.loadTodaysKpi = this.loadTodaysKpi.bind(this); } render(){ console.log(this.props.startDate + " "+ this.props.endDate); return <div className="today-kpi"> </div>; } loadTodaysKpi(){ console.log("AAAA"); } } 我该如何实现呢?
由于我还没有掌握的原因,React不鼓励从父母那里调用子方法.然而,他们放松并给我们一个“逃生舱”,允许这样做.你认为’Refs’是逃生舱的一部分是正确的.如果像我一样,您已经阅读了数十篇搜索此信息的文章,那么您将准备好了解他们的
description of the escape hatch
在您的情况下,您可能希望在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对于调用儿童方法的厌恶. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |