【问题标题】:how to add a react date picker no hooks如何添加反应日期选择器没有钩子
【发布时间】:2021-12-02 13:31:04
【问题描述】:

我正在做一个反应项目,尝试使用 npm react-datepicker 添加反应日期选择器。我正在使用 this.state 和 handleChange(e)。如何在不使用钩子的情况下在我的 react 应用上添加日期选择器?

【问题讨论】:

    标签: reactjs npm


    【解决方案1】:

    这是App组件中的连接示例,它在reactjs中使用日期选择器的旧方法,

    你的进口是,

    import React, { Component } from 'react';
    import DatePicker from 'react-datepicker';
    

    应用程序将是,

    class App extends Component {
    
      constructor (props) {
        super(props)
        this.state = {
          startDate: new Date()
        };
        this.handleChange = this.handleChange.bind(this);
        this.onFormSubmit = this.onFormSubmit.bind(this);
      }
    
      handleChange(date) {
        this.setState({
          startDate: date
        })
      }
    
      onFormSubmit(e) {
        e.preventDefault();
        console.log(this.state.startDate)
      }
     
      render() {
        return (
          <form onSubmit={ this.onFormSubmit }>
            <div className="form-group">
              <DatePicker
                  selected={ this.state.startDate }
                  onChange={ this.handleChange }
                  name="startDate"
                  dateFormat="MM/dd/yyyy"
              />
              <button className="btn btn-primary">Show Date</button>
            </div>
          </form>
        );
      }
      
    }
    
    export default App;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-06-11
      • 2021-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-29
      • 2020-10-12
      • 2021-01-10
      相关资源
      最近更新 更多