使用React的bootstrap-datepicker:onClick时onChange不会触发

时间:2016-04-20 12:10:40

标签: reactjs javascript-events bootstrap-datepicker

考虑以下组件:

let Thing = React.createClass({
  componentDidMount: function() {
    $(ReactDOM.findDOMNode(this.refs.date)).datepicker()
  },

  myHandler: function() {
    console.log('handling!');
  }

  render: function() {
    return (
      <div ref="date" className="input-group date pull-right">
        <input ref="myRef" type="text" className="form-control"
               onChange={this.myHandler}/>
      </div>
    );
  }
});
当我更改文本字段的值时,不会调用myHandler()。

事情是,如果我用onClick替换onChange并单击输入,myHandler 触发,所以它看起来不像上下文或任何事情。

为什么不改变工作? 我使用的是React v0.14.3,bootstrap-datepicker v1.7.0-dev

2 个答案:

答案 0 :(得分:2)

尝试修改componentDidMount函数,如下所示:

componentDidMount: function() {
  $(ReactDOM.findDOMNode(this.refs.date)).datepicker()
  var _this = this;
  $(ReactDOM.findDOMNode(this.refs.date)).on('changeDate', function(e) {
    _this.handleChange(e);
  })
}

答案 1 :(得分:0)

这里是使用react-bootstrap-datepicker的Custom Date Picker Component的示例 包含开始日期和结束日期

From To Date Datepicker with validation handler

import React, { Component } from "react";
import PropTypes from "prop-types";
import DatePicker from "react-bootstrap-date-picker";
import { FormGroup, Col, HelpBlock, ControlLabel } from "react-bootstrap";
import validationError from "../../utils/validation";

export default class DateSelector extends Component {
  constructor(props) {
    super(props);
    this.state = {
      fromDate: props.fromDate || new Date().toISOString(),
      toDate: props.toDate || new Date().toISOString(),
      validationState: {
        fromDate: null,
        toDate: null
      }
    };
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (
      this.state.fromDate !== nextProps.fromDate ||
      this.state.toDate !== nextProps.toDate
    ) {
      this.setState({
        fromDate: nextProps.fromDate,
        toDate: nextProps.toDate
      });
    }
  }
  //setMax selectable Date
  setMaxDate = () => {
    const aYearFromNow = new Date();
    return new Date(
      aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1)
    ).toISOString();
  };

  renderError = () => {
    return this.state.toDate >= this.state.fromDate ? null : (
      <HelpBlock>{validationError.DATE_VALIDATION_ERROR}</HelpBlock>
    );
  };

  //check for to date is greater than from value and set error in state
  validateDates = () => {
    this.state.toDate < this.state.fromDate
      ? this.setState({
          validationState: { toDate: null }
        })
      : this.setState({
          validationState: { toDate: "error" }
        });
  };

  //function to handle To(End) Date onChange
  toDateHandleChange = date => {
    this.setState({
      toDate: date
    });
    this.validateDates();
    //send data to parent component
    this.props.dateHandler({ fromDate: this.state.fromDate, toDate: date });
  };
  //function to handle From(start) Date onChange
  fromDateHandleChange = date => {
    this.setState({
      fromDate: date
    });
    this.validateDates();
    //send data to parent component
    this.props.dateHandler({ fromDate: date, toDate: this.state.toDate });
  };
  renderToDate = ( toDate, fromDate, validationState) => {
    return  (
      <FormGroup controlId="toDate" validationState={validationState.toDate}>
        <Col componentClass={ControlLabel} sm={2}>
          To
        </Col>
        <Col sm={4}>
          <DatePicker
            disabled={editable}
            id="to-date-dt"
            value={toDate}
            minDate={fromDate}
            onChange={this.toDateHandleChange}
          />
          {this.renderError()}
        </Col>
      </FormGroup>
    );
  };

  buildComponent = (props, state) => {
    const { fromDate, toDate, validationState } = state;
    return (
      <div>
        <FormGroup
          controlId="fromDate"
          validationState={this.state.validationState.fromDate}
        >
          <Col componentClass={ControlLabel} sm={2}>
            From
          </Col>
          <Col sm={4}>
            <DatePicker
              id="from-date-dt"
              value={fromDate}
              minDate={new Date().toISOString()}
              maxDate={this.setMaxDate()}
              onChange={this.fromDateHandleChange}
            />
            {this.renderError()}
          </Col>
        </FormGroup>
        {this.renderToDate(toDate, fromDate, validationState)}
      </div>
    );
  };
  render() {
    return this.buildComponent(this.props, this.state);
  }
}

DateSelector.propTypes = {
  fromDate: PropTypes.string,
  toDate: PropTypes.string,
  dateHandler: PropTypes.func.isRequired,
};
  

在组件中,您可以按以下方式使用

dateHandler = data => {
    this.setState({
      fromDate: data.fromDate,
      toDate: data.toDate
    });
  };

<DateSelector
              fromDate={fromDate}
              toDate={toDate}
              dateHandler={this.dateHandler}
            />