获取对 antd 时间选择器的引用并将其值存储到状态变量

Get reference to a antd time picker and store its value to state variable

我需要获取用户在时间选择器中选择的值以存储在状态中。在antd timepicker文档中我无法引用参数。

代码:

const format = "HH:mm";

export default function MyTimePicker() {
  const [mytime, setTime] = useState("00:00");

  const handleChange = (e) => {
    setTime(e.targe.value);
    console.log(mytime);
  };

  return (
    <TimePicker
      defaultValue={moment("12:08", format)}
      format={format}
      onChange={handleChange}
    />
  );
}

显示

Cannot read property 'value' of undefined

文档里只有onSelect和onChange,但是如何获取选中的值呢?

当您需要仅在用户单击“确定”按钮时更新状态时使用onOk。否则使用 onChangeonSelect

  const [timeString, setTimeString] = useState('');

  return (
    <TimePicker
      onOk={(time) => {
        setTimeString(timeString);
        console.log(time);
        console.log(timeString);
      }}
    />
  );

在文档中 https://ant.design/components/time-picker/ looks like onOk is not presented but you can find onOk description here https://ant.design/components/date-picker/#RangePicker

当您使用 onChange 时,您应该使用带有参数的 handle 函数:(time, timeString)