反应日期时间;我正在使用二合一组件,我如何分辨哪个是哪个?

React-Datetime; I'm using two in one component, how do I tell which is which?

这是一个关于 react-datetime 的奇怪问题:为什么回调不允许 returned 一个“名字”?

我在日历调度程序上两次使用白天作为“开始”和“结束”时间。但我想使用单个“onChange”事件来更新状态。问题是:Datetime onChange 只有 return 时间,它没有 return 名称或 ID 或任何让我识别 哪个 Datetime 组件的方式正在发送 onChange。

这里是 render() 代码:

<CardSubtitle>Start Date:
  <Datetime 
    value = {this.state.start}
    onChange={this.handleChange}
    className = "dateTimeModule"
  />
</CardSubtitle>

<CardSubtitle>End Date:
  <Datetime 
    value = {this.state.end}
    onChange={this.handleChange}
    className = "dateTimeModule"
  />
</CardSubtitle>

这是我要使用的逻辑:

handleChange = (e) => {

  this.setState({
    bodyEdit: true,
    [e.target.name]:e.target.value
  })
};

但是“e”只包含日期对象。日期时间似乎不支持“名称”return?

我很困惑,这似乎是一个明显的失误。我如何区分这些?我需要为每个函数编写单独的函数吗?

考虑这样做:

handleStartChange = (e) => {
  this.setState({
    startDate: e
  })
};

handleEndChange = (e) => {
  this.setState({
    endDate: e
  })
};

但这似乎是不必要的代码。

你可以做的是给你自己传递一个额外的参数给你的函数:

        <CardSubtitle>Start Date:
          <Datetime 
            value = {this.state.start}
            onChange={(e) => this.handleChange(e, "start")}
            className = "dateTimeModule"
          />
        </CardSubtitle>

        <CardSubtitle>End Date:
          <Datetime 
            value = {this.state.end}
            onChange={(e) => this.handleChange(e, "end")}
            className = "dateTimeModule"
          />
        </CardSubtitle>

并在您的 handleChange(e, name) 函数中重复使用此参数:

  handleChange = (e, name) => {
    this.setState({
      bodyEdit: true,
      [name]:e
    })
  };

还要确保你正在使用的库返回的是什么作为“e”,它似乎不是一个经典事件而是一个矩对象:

Callback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).