【问题标题】:React: Cant call a function inside child component反应:无法在子组件内调用函数
【发布时间】:2015-12-06 18:10:49
【问题描述】:

我试图通过 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");
    }
}

我应该如何实现这个?

【问题讨论】:

    标签: function reactjs call


    【解决方案1】:

    由于我还不明白的原因,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;
    

    在渲染方法之上并在 ref 回调函数中使用“self”。

    在我的例子中,我有未知数量的动态生成的子组件,所以我将每个子组件放入一个数组中。我清除了 componentWillUpdate 中的数组。这一切似乎都在起作用,但我有一种不安的感觉,尤其是考虑到 React 讨厌调用儿童方法。

    【讨论】:

      【解决方案2】:

      如果你想在子进程内部调用函数/方法,你应该把它从父进程传递给子进程。您需要更改的另一件事是 onUpdateonChange,假设您要跟踪对该字段的每一次更改。另一种选择是检查它何时为onSubmit,但听起来您希望每次更新字段时都发生这种情况。

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 1970-01-01
        • 2020-07-13
        • 1970-01-01
        • 2020-12-06
        • 2020-01-18
        • 1970-01-01
        • 2021-04-09
        • 2021-03-12
        相关资源
        最近更新 更多