【问题标题】:Default Value in react-datepickerreact-datepicker 中的默认值
【发布时间】:2017-09-13 21:31:35
【问题描述】:

我在我的 react-redux 应用程序中使用 react-datepicker 模块,我使它与 redux 形式兼容,如下所示:

const MyDatePicker = props => (
  <div>
    <DatePicker
      {...props.input}
      dateFormat="DD-MM-YYYY"
      selected={props.input.value
        ? moment(props.input.value, 'DD-MM-YYYY')
        : null}
      placeholderText={props.placeholder}
      disabled={props.disabled}
    />
    {
      props.meta.touched && props.meta.error &&
      <span className="error">
        { props.intl.formatMessage({ id: props.meta.error }) }
      </span>
    }
  </div>
);

问题是我不知道如何在我的模块中添加默认值。此默认值必须是今天。关于如何处理这个问题的任何想法?

【问题讨论】:

  • 试试这个,selected={props.input.value ? moment(props.input.value, 'DD-MM-YYYY') : moment()}
  • 不错,它奏效了。谢谢!!
  • 太好了。欢迎。

标签: reactjs datepicker default-value redux-form


【解决方案1】:

您应该使用moment(dt).format() 来格式化日期

const MyDatePicker = props => {
  var date = new Date();
  var todayDate = moment(date).format('DD-MM-YYYY');
  return (
  <div>
    <DatePicker
      {...props.input}
      dateFormat="DD-MM-YYYY"
      selected={props.input.value
        ? moment(props.input.value).format('DD-MM-YYYY')
        : todayDate}
      placeholderText={props.placeholder}
      disabled={props.disabled}
    />
    {
      props.meta.touched && props.meta.error &&
      <span className="error">
        { props.intl.formatMessage({ id: props.meta.error }) }
      </span>
    }
  </div>
  );
}

【讨论】:

    【解决方案2】:

    您可以在mapStateToProps 阶段指定初始表单值:

    const mapStateToProps = state => {
      return {
        initialValues: {
          date: moment()
        } // Use the `initialValues` property to set your initial data
      };
    }
    

    这里也有解释:http://redux-form.com/6.6.3/examples/initializeFromState/

    【讨论】:

      【解决方案3】:

      改变:

       selected={props.input.value
              ? moment(props.input.value, 'DD-MM-YYYY')
              : null}
      

      t0

       selected={props.input.value ? moment(props.input.value, 'DD-MM-YYYY') : moment()}
      
      
      const MyDatePicker = props => (
        <div>
          <DatePicker
            {...props.input}
            dateFormat="DD-MM-YYYY"
        selected={props.input.value ? moment(props.input.value, 'DD-MM-YYYY') : moment()}
            placeholderText={props.placeholder}
            disabled={props.disabled}
          />
          {
            props.meta.touched && props.meta.error &&
            <span className="error">
              { props.intl.formatMessage({ id: props.meta.error }) }
            </span>
          }
        </div>
      );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-08
        • 2014-01-17
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-04-19
        • 1970-01-01
        相关资源
        最近更新 更多