为什么使用formik useField时不显示错误?

问题描述 投票:0回答:1

我的任务是编写代码来选择日期。
这是我现在所拥有的:

export let DatePicker = ({ label, ...props }) => {
  let [field, meta, helpers] = useField(props.name)
  let { value, touched, error } = meta
  if(value === null)
    value = {}
  let { setValue, setTouched, setError } = helpers
  let days = [], meses = []
  for(let i = 1; i <= 31; i++)
    days.push(i)
  for(let i = 1; i <= 12; i++)
    meses.push(i)
  console.log(error)
  return (
    <div>
      <p>{label}</p>
      <select>
        {days.map(day => (
          <option
            onClick={() => {
              setValue({ ...value, day })
              setTouched(true)
              if(value.day === undefined || value.mes === undefined)
                setError('Error!')
            }}
            key={day} value={day} label={day}
          />
        ))}
      </select>
      <select>
        {meses.map(mes => (
          <option
            onClick={() => {
              setValue({ ...value, mes })
              setTouched(true)
              if(value.day === undefined || value.mes === undefined)
                setError('Error!')
            }}
            key={mes} value={mes} label={mes}
          />
        ))}
      </select>
      {touched && error && (
        <div className="form_error">{error}</div>
      )}
    </div>
  )
}

在控制台中我看到“错误!”首先显示,然后立即取消定义。我不明白问题是什么,请帮助谁

reactjs formik react-forms
1个回答
0
投票

const [field, meta] = useField({ ...props, name: props.name, id: props.name });

const formik = useFormikContext();

if (formik.submitCount > 0) {
    meta.touched = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.