在React

时间:2016-11-30 23:22:13

标签: function reactjs components

我正在尝试将一个名为updateTime的函数从我的父组件传递给子组件。

子组件加载完全正常,但是当调用handleApply时,它会尝试调用this.props.updateTime但会抛出错误:

this.props.updateTime is not a function

父组件

class ParentComponent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      startDate: moment(),
      endDate: moment().add(21, 'days'),
      minDate: moment(),
    };
    this.updateTime = this.updateTime.bind(this);
  }

    updateTime(startDate, endDate) {
      this.setState({
        startDate: startDate,
        endDate:endDate
      });
    }

  render() {
    return (
      <div>
          <DatePicker startDate={this.state.startDate} endDate={this.state.endDate} minDate={this.state.minDate} updateTime={this.props.updateTime}/>
      </div>
    )

子组件:

class DatePicker extends Component {
  constructor(props) {
    super(props);
    this.handleApply = this.handleApply.bind(this);
  }


 handleApply(event, picker) {
  console.log("updating the time");
   this.props.updateTime(picker.startDate, picker.endDate);
  }


render() {
    const {startDate, endDate, minDate, updateTime} = this.props;

    let start = this.props.startDate.format('MMMM Do YYYY h:mm a');
    let end = this.props.endDate.format('MMMM Do YYYY h:mm a');
    let label = start + ' - ' + end;

    let locale = {
      format: 'MMMM do YYYY, h:mm:ss a',
      separator: ' - ',
      applyLabel: 'Apply',
      cancelLabel: 'Cancel',
      weekLabel: 'W',
      customRangeLabel: 'Custom Range',
      daysOfWeek: moment.weekdaysMin(),
      monthNames: moment.monthsShort(),
      firstDay: moment.localeData().firstDayOfWeek(),
    };

    return (
      <div className="form-group">
        <div className="date-time-range-picker">
          <DatetimeRangePicker
            timePicker
            timePicker24Hour
            showDropdowns
            timePickerSeconds
            locale={locale}
            minDate = {this.props.minDate}
            startDate={this.props.startDate}
            endDate={this.props.endDate}
            onApply={this.handleApply}>
            <div className="input-group">
              <input type="text" className="form-control" value={label}/>
                <span className="input-group-btn">
                    <Button className="default date-range-toggle">
                      <i className="fa fa-calendar"/>
                    </Button>
                </span>
            </div>
          </DatetimeRangePicker>
        </div>
        <div className="error">{error} </div>
      </div>
    );
  }

1 个答案:

答案 0 :(得分:1)

您需要在组件中正确引用updateTime功能:

<DatePicker ... updateTime={this.props.updateTime}/>

为:

<DatePicker ... updateTime={this.updateTime}/>