react-datepicker 中的默认值

Default Value in react-datepicker

我在我的 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>
);

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

你应该使用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>
  );
}

您可以在 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/

变化:

 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>
);