【问题标题】:Get reference to a antd time picker and store its value to state variable获取对 antd 时间选择器的引用并将其值存储到状态变量
【发布时间】:2021-10-07 14:04:03
【问题描述】:

我需要获取用户在时间选择器中选择的值以存储在状态中。在 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}
    />
  );
}

显示

无法读取未定义的属性“值”

文档只有 onSelect 和 onChange 但是如何获取选定的值?

【问题讨论】:

    标签: reactjs antd timepicker ant-design-pro


    【解决方案1】:

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

      const [timeString, setTimeString] = useState('');
    
      return (
        <TimePicker
          onOk={(time) => {
            setTimeString(timeString);
            console.log(time);
            console.log(timeString);
          }}
        />
      );

    在文档中 https://ant.design/components/time-picker/ 看起来像 onOk 没有显示,但您可以在此处找到 onOk 描述 https://ant.design/components/date-picker/#RangePicker

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

    【讨论】:

    • 完美!谢谢
    • 除了 time, timeString 还有什么?因为仅使用 time 或 timeString 输入时间并将它们存储在 ("0222" -->02:22) 格式的状态中需要大量代码
    • @SaiKrishnadas 您可以通过time.format(format) 使用您想要的任何格式。示例codesandbox.io/s/antd-reproduction-template-forked-qqe5k?file=/…
    • 尝试相同的 RangePicker 失败。它说time.format is not a function
    • @SaiKrishnadas RangePicker 不提供一个 time 作为参数。 RangePicker 使用两个日期,因此onChange 签名其function(dates: [moment, moment], dateStrings: [string, string]) 其中第一个参数dates 其日期数组和日期。
    猜你喜欢
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    相关资源
    最近更新 更多