【问题标题】:timepicker component in reactjsreactjs中的时间选择器组件
【发布时间】:2017-09-13 01:58:15
【问题描述】:

我开发了一个简单的时间选择器组件。

这个组件的功能是

a) 以 12 小时格式和 24 小时格式显示时间

b) 用户可以选择小时、分钟、上午、下午

c) 将时间发送到服务器时,时间应为 24 小时格式

目前我看到的错误是如果时间是 PM 格式,则在初始加载时,不会显示 24 小时时间

任何人都可以查看代码并帮助我改进我的代码并修复一个错误吗?

下面是带demo的代码

import React from "react";
import moment from "moment";
import "./time.css";

class TimePicker extends React.PureComponent {
  constructor(props) {
    super(props);
    this.calculateMeridian(props.time);
    this.state = {
      time: this.convertTime(props.time),
      hour: this.calculateHour(props.time),
      hourTime: this.convertTime(props.time),
      selectedNumber: 1,
      meridian: this.calculateMeridian(props.time),
      minutes: this.calculateMinutes(props.time),
      hasError: false
    };
  }

  convertTime = time => {
    const splittedTime = time && time.split(":");
    const hour = splittedTime && splittedTime[0];
    if (hour > 12) {
      // const hour = time.split(':')[0];
      const momentInstance = moment(time, "hhmm");
      const twelveHourTime = momentInstance.format("h:mm");
      console.log("twelveHourTime", twelveHourTime);
      return twelveHourTime;
    }

    return time;
  };

  calculateMinutes = time => {
    const splittedTime = time && time.split(':');
    console.log('minutes', splittedTime);
    return splittedTime[1].split(' ')[0];
  }

  calculateHour = time => {
    const splittedTime = time && time.split(':');
    return splittedTime[0];
  }

  calculateMeridian = time => {
    const splittedTime = time && time.split(':')[1].split(' ');
    console.log('splitted time', splittedTime);
    return splittedTime[1];
  }

  handleClick(time) {
    const { meridian, minutes } = this.state;
    const hourTime = moment(`${time}:${minutes}`, [
      "hhmm A"
    ]).format("h:mm");
    this.setState(
      {
        time,
        hour: time,
        selectedNumber: time,
        hourTime
      },
      () => this.props.onClick(hourTime)
    );
  }

  handleTimeAmPm(meridian) {
    const { time, minutes, hour } = this.state;
    const hourTime = moment(`${hour}:${minutes} ${meridian}`, [
      "h:mm A"
    ]).format("h:mm");
    console.log('hourTime', hourTime);
    this.setState({ meridian, hourTime }, () => this.props.onClick(this.state.hourTime));
  }

  handleMinutes = e => {
    const { value, min, max } = e.target;
    if (value >= min && value < max) {
      const hourTime = moment(
        `${this.state.hour}:${value}}`,
        ["hhmm"]
      ).format("h:mm a");
      if (value.length < 2) {
        this.setState({ minutes: "0" + value.slice(-2), hourTime }, () =>
          this.props.onClick(this.state.hourTime)
        );
      } else {
        this.setState({ minutes: value.slice(-2), hourTime }, () =>
          this.props.onClick(this.state.hourTime)
        );
      }
    } else {
      this.setState({ minutes: "00", hasError: true });
    }
  };

  render() {
    let time = [];
    for (let i = 1; i <= 12; i++) {
      time.push(
        <div
          className={this.state.selectedNumber === i ? "hand selected" : "hand"}
          key={i}
          onClick={() => this.handleClick(i)}
        >
          {i}
        </div>
      );
    }
    console.log('time', this.state.hourTime);
    return (
      <div className="card card-md" style={{ width: "100%", maxWidth: "100%" }}>
        <div className="time-date">
          <div className="display">
            <div className="content">
              <div className="main-title">
                {this.state.hour}:{this.state.minutes}{this.state.meridian}
              </div>
            </div>
          </div>
          <div className="control">
            <div className="slider">
              <div className="time-control">
                <div className="clock">
                  <div className="clock-face">
                    <div className="center" />
                    {time}
                  </div>
                </div>
                <div className="actions">
                  <div className="am" onClick={() => this.handleTimeAmPm("am")}>
                    am
                  </div>
                  <div className="minutes">
                    <div className={this.state.hasError && "input error"}>
                      <input
                        type="number"
                        min={0}
                        max={60}
                        value={this.state.minutes}
                        onChange={this.handleMinutes}
                      />
                    </div>
                  </div>
                  <div className="pm" onClick={() => this.handleTimeAmPm("pm")}>
                    pm
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}

export default TimePicker;

演示

https://codesandbox.io/s/o53r9nr9z5

【问题讨论】:

    标签: javascript reactjs ecmascript-6 momentjs


    【解决方案1】:

    只需在 componentDidMount 中调用您的 am/pm 处理程序。

    componentDidMount() {
      this.handleTimeAmPm(this.state.meridian);
    }
    

    【讨论】:

      猜你喜欢
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 2018-04-25
      相关资源
      最近更新 更多