加上至今保存在状态中的天数

时间:2018-07-19 20:22:26

标签: javascript reactjs

在我的react组件中,我有一个类型为date的输入字段。选择日期后,它将保存在状态中。在另一个地方,我想为此日期添加一定天数并显示它。我发现了这样的Javascript解决方案(Add days to JavaScript Date),但不幸的是无法在我的react / state环境中使用它。任何有关如何实现这一目标的帮助将不胜感激。谢谢!

旁注:我正在使用本地http服务器加载form.js

index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
</head>
<body>
    <div class="form-container container col-8 my-4"></div>

    <script src="https://unpkg.com/react@16/umd/react.development.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js" crossorigin></script>
    <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>

    <!-- Load our React component. -->
    <script type="text/babel" src="form.js" crossorigin></script>
</body>

form.js

'use strict';

const e = React.createElement;

class testForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        birthday: ''
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
      this.setState({ 
          birthday: event.target.value
        });
  }

  render() {
    return (
        <form>
            <div className="row">

                <div className="form-group">
                <label htmlFor="birthday">Birthday</label>
                <input type="date" className="form-control" id="birthday" value={this.state.birthday} onChange={this.handleChange} placeholder="TT.MM.JJJJ" />
                </div>

            </div>

            <div>Show date +7 days</div>
            <div>{this.state.birthday}</div>
        </form>
    );
  }
}

const domContainer = document.querySelector('.form-container');
ReactDOM.render(e(testForm), domContainer);

3 个答案:

答案 0 :(得分:1)

可以使用以下功能将天添加到给定日期。

gm.exe convert test.jpg

这使事情变得简单,并使代码相当可靠和可读。通过以这种方式创建日期,月份和年份会根据使用的月份中的日期自行调整。因此,如果它是一个负数,它将去到前几个月,甚至可能是几年,反之则是更大的正数。

答案 1 :(得分:0)

使用moment.js Moment.js's .add()

import moment from 'moment'   

class testForm extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
        birthday: moment().format('DD-MM-YYYY'),
    };

    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(event) {
      this.setState({ 
          birthday: moment(event.target.value, 'DD-MM-YYYY')
        });
  }

  render() {
    const { birthday } = this.state

    const birthdayWithAddedSevenDays = birthday.add('days', 7)

    return (
        <form>
            { /* ... */ }

            <div>Show date +7 days</div>
            <div>{ birthdayWithAddedSevenDays }</div>
        </form>
    );
  }
}

开箱即用地处理边缘案例非常简单。

答案 2 :(得分:0)

如果您需要一个简单的解决方案,则可以在codesandbox上查看我的示例。

这是一个原始示例:

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      birthday: ""
    };
  }

  handleBirthdayChange = event => {
    this.setState({
      birthday: event.target.value
    });
  };

  getDateInFuture = (leftBoundary, days) => {
    // Check if date is valid
    // e.g. '' -> invalid, '2018-01-01' -> valid, '1532034952667' -> invalid
    const isDateValid = Date.parse(leftBoundary);

    if (isDateValid) {
      const date = new Date(leftBoundary);
      const dateInFuture = new Date().setDate(date.getDate() + days);

      return new Date(dateInFuture);
    }

    // If date is incorrect, return today
    return new Date();
  };

  render() {
    return (
      <div className="App">
        <div>
          <label for="birthday">Birthday</label>
          <input
            id="birthday"
            type="date"
            value={this.state.birthday}
            onChange={this.handleBirthdayChange}
          />
        </div>
        <div>
          <p>
            The day in future:
            {this.getDateInFuture(this.state.birthday, 7).toString()}
          </p>
        </div>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);