无法从父反应组件调用子反应组件的属性

时间:2018-10-07 04:44:45

标签: reactjs

以下是jsx个父反应组件的child & parent代码。 我正在尝试将数据从子React组件传递到父React组件作为属性(generateReport,但是它将错误抛出

  

未捕获的TypeError:this.props.generateReport不是函数       在MetricsReport.generateReport(metrics-report.jsx:40)

child.jsx

import React, { Component } from 'react';
import {
  Row,
  Col,
  Input,
  Collapsible,
  CollapsibleItem
} from 'react-materialize';

class MetricsReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      metricsParams: { reportType: '' }
    };
    this.getReportType = this.getReportType.bind(this);
    // Add the below line as per the answer but still facing the problem
    this.generateReport = this.generateReport.bind(this);
  }
  getReportType(event) {
    console.log(this.state.metricsParams);
    let metricsParams = { ...this.state.metricsParams };
    metricsParams.reportType = event.target.value;
    this.setState({ metricsParams });
  }

  generateReport() {
    this.props.generateReport(this.state.metricsParams);
  }
  componentDidMount() {}

  render() {
    return (
      <div class="ushubLeftPanel">
        <label>{'Report Type'}</label>
        <select
          id="metricsDropDown"
          className="browser-default"
          onChange={this.getReportType}
        >
          <option value="MetricsByContent">Metrics By Content</option>
          <option value="MetricsByUser">Metrics By User</option>
        </select>
        <button onClick={this.generateReport}>Generate Report</button>
      </div>
    );
  }
}

export default MetricsReport;

parent.jsx

import React, { Component } from 'react';
import MetricsReport from '../components/pages/metrics-report';

class MetricsReportContainer extends Component {
  constructor(props) {
    super(props);
    this.generateReport = this.generateReport.bind(this);
  }
  generateReport(metricsParams) {
    console.log(metricsParams);
  }
  componentDidMount() {}
  render() {
    return (
      <div>
        <MetricsReport generateReport={this.generateReport} />
      </div>
    );
  }
}

export default metricsReportContainer;

2 个答案:

答案 0 :(得分:0)

您忘记将上下文this绑定到子组件MetricsReport中:

// inside the constructor
this.generateReport = this.generateReport.bind(this);

但是您可以这样简单地使用:

<button 
  onClick={this.props.generateReport(this.state.metricsParams)}
>
  Generate Report
</button>

答案 1 :(得分:0)

您可以通过使用匿名函数而不是普通函数来处理这些情况。匿名函数可以解决您的问题,并消除了绑定的必要。

generateReport(metricsParams) { console.log(metricsParams); }

成为

generateReport = (metricsParams) => { console.log(metricsParams); }

也在子班

generateReport() { this.props.generateReport(this.state.metricsParams); }

成为

generateReport = () => { var metricsParams = this.state.metricsParams; this.props.generateReport(metricsParams); }