在antd设计中使用DatePicker和Form FormItem做出反应

时间:2018-04-15 11:14:22

标签: reactjs antd

    <FormItem {...formItemLayout} label="Publish Date">
      {getFieldDecorator('publishDate', {
        initialValue: '',
        rules: [
          {
            required: false,
            message: 'Please input publishDate',
            whitespace: true,
          },
        ],
      })(<DatePicker onChange={onChange} />)}
    </FormItem>

不起作用。我得到异步验证器说&quot; publishDate不是字符串&#39;。

所以我以这种方式使用它作为临时解决方案。

<FormItem {...formItemLayout} label="Publish Date">
  {getFieldDecorator('publishDate', {
    initialValue: getCurrentDate(),
    rules: [
      {
        required: false,
        message: 'Please input publishDate',
        whitespace: true,
      },
    ],
  })}
  <DatePicker onChange={onChange} />
</FormItem>

任何帮助?提前谢谢!

2 个答案:

答案 0 :(得分:2)

应该在规则中使用type: 'object'

<FormItem {...formItemLayout} label="Publish Date">
  {getFieldDecorator('publishDate', {
    initialValue: moment(),
    rules: [
      {
        type: 'object',
        required: false,
        message: 'Please input publishDate',
        whitespace: true,
      },
    ],
  })(<DatePicker/>)}
</FormItem>

此外,您不需要onChange处理程序。

答案 1 :(得分:0)

const makeDateField = Component => ({
  input,
  meta,
  children,
  hasFeedback,
  label,
  labelRight,
  ...rest
}) => {
  /* eslint-disable no-underscore-dangle */
  const hasError = meta.touched && meta.invalid;

  input = {
    ...input,
    value: input.value && input.value._isValid ? moment(input.value) : moment(),

  };
  return (
    <FormItem
      {...formItemLayout}
      label={label}
      validateStatus={hasError ? 'error' : 'success'}
      hasFeedback={hasFeedback && hasError}
      help={hasError && meta.error}
    >
      <Component 
        {...input} 
        {...rest}
        onChange={(event, value) => input.onChange(event)} 
        onBlur={(event, value) => input.onBlur(value) } 
      >
        {children}
      </Component>
      {labelRight && <span style={{ color: '#9e9e9e' }}>{labelRight}</span>}
    </FormItem>
  );
};

export const ADatePicker = makeDateField(DatePicker);

使用形式

   <Field
     label="Start Date"
     placeholder="Start Date"
     name="startDate"
     component={ADatePicker}
   />