首页 > 解决方案 > 如何从 ReactJS 中的另一个类调用方法?

问题描述

我有两个类,主要的一个,另一个是 PopUp。我在主类中有一个显示模态的按钮,然后在我单击一个按钮后,弹出窗口将关闭,如果我单击该按钮,我想从另一个类执行一个函数。

如何导出该方法并在模态类中导入?

这是我的方法:

async getKPIs(year, period) {
      try {
        var payloadData = {
          GroupKey: this.props.data.groupkey,
          FamilyKey: this.props.data.id,
          FiscalYear: year,
          PID: period,
        };
        const response = await axios.post(
          config.kpi.getFiscalYearKPIs,
          JSON.stringify(payloadData)
          , { 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-api-key': kpiKey } });

        if (response.status !== 200) {
          this.setState({ failed: true });
          return;
        }
        const kpis = response.data['/kpiinput/view/all'].kpiInput.map(kpi => {
          return {
            GROUP_KEY: kpi.GROUP_KEY,
            FAMILY_KEY: kpi.FAMILY_KEY,
            KPI_KEY: kpi.KPI_KEY,
            KPIFISCALYEAR: kpi.KPIFISCALYEAR,
            KPI_NAME: kpi.KPI_NAME,
            KPI_ORDER: kpi.KPI_ORDER,
            UOM_NAME: kpi.UOM_NAME,
            TYPE_NAME: kpi.TYPE_NAME,
            OPERATOR_NAME: kpi.OPERATOR_NAME,
          };
        });

        this.setState({ kpis, failed: false });
        this.getColumns(period);
      } catch (err) {
        this.setState({ failed: true });
        console.error(err);
      }
    }

这就是我想在模式类中调用它的地方,当我关闭 Swal 时:

 async approveKPI(e) {
    e.preventDefault();
    var InputValue = this.state.Actualvalue

    if(InputValue){
      try {
      var kpikey = document.getElementById('kpikey').innerText;
      var period = document.getElementById('period').innerText;
      //var typekey = document.getElementById('typekey').innerText;
      var typekey = this.state.CurrentType
      var payloadData = [{
        KPIInputKey: kpikey,
        KPIInputTypeKey: typekey,
        KPIStatus: this.state.derived,
        PID: period,
      }];
      const response = await axios.post(
        config.kpi.approveKPI,
        JSON.stringify(payloadData)
        , { 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-api-key': kpiKey } });
      if (response.status !== 201) {
        this.setState({ failed: true });
        return;
      } else if (response.status === 201) {
        Swal.fire({
          type: 'success',
          title: 'Data Approved Successfully',
        }).then(function () {
          **//Here I want to call the method from the other class**
        });
      }
      this.setState({ show: false });
    } catch (err) {
      Swal.fire({
        type: 'error',
        title: 'Something went Wrong',
        text: 'Try Again',
      }).then(function () {
        //window.location.reload();
      });
      console.log('Error' + err);
      this.setState({ failed: true });
      console.error(err);
    }
    }
    else {
      Swal.fire({
        type: 'warning',
        title: 'Input field empty',
        text: 'Please fill input field',
      })
    } 
  }

标签: reactjs

解决方案


Alberto,我们认为模态是该组件的子组件,就像您要发送的方法一样。

因此,在渲染ApprovePopup模式时,将函数作为属性传递给它,例如:

<ApprovePopup row={row} disabled={true} getKPIs={this.getKPIs}/>

然后,在模态的其他功能内approveKPI

 async approveKPI(e) {
    e.preventDefault();
    var InputValue = this.state.Actualvalue;
    const { getKPIs } = this.props; //destructive declaration for getKPIs

    if(InputValue){
      try {
      var kpikey = document.getElementById('kpikey').innerText;
      var period = document.getElementById('period').innerText;
      //var typekey = document.getElementById('typekey').innerText;
      var typekey = this.state.CurrentType
      var payloadData = [{
        KPIInputKey: kpikey,
        KPIInputTypeKey: typekey,
        KPIStatus: this.state.derived,
        PID: period,
      }];
      const response = await axios.post(
        config.kpi.approveKPI,
        JSON.stringify(payloadData)
        , { 'headers': { 'Accept': 'application/json', 'Content-Type': 'application/json', 'x-api-key': kpiKey } });
      if (response.status !== 201) {
        this.setState({ failed: true });
        return;
      } else if (response.status === 201) {
        Swal.fire({
          type: 'success',
          title: 'Data Approved Successfully',
        }).then(function () {
          **//Here I want to call the method from the other class**
          getKPIs(); //we are using the function we sent as props to the modal
        });
      }
      this.setState({ show: false });
    } catch (err) {
      Swal.fire({
        type: 'error',
        title: 'Something went Wrong',
        text: 'Try Again',
      }).then(function () {
        //window.location.reload();
      });
      console.log('Error' + err);
      this.setState({ failed: true });
      console.error(err);
    }
    }
    else {
      Swal.fire({
        type: 'warning',
        title: 'Input field empty',
        text: 'Please fill input field',
      })
    } 
  }

阅读有关组件与其子级之间的回调关系的更多信息。


推荐阅读