reactjs 如何在react flatpickr上单击按钮时获取值

pkln4tw6  于 2023-08-04  发布在  React
关注(0)|答案(1)|浏览(121)

我在react中有一个组件,并附加react-flatpicker来获取日期值。然而,在我使用useRef之后,它显示值“可能为null”,并且在console.log之后是相同的结果

<Flatpickr
                          ref={fp}
                          name="startTime"
                          className="py-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
                          options={{
                            enableTime: true,
                            noCalendar: true,
                            dateFormat: "H:i",
                          }}
                        />

字符串
这里是函数

const fp = useRef(null);
function handleSubmitAgenda() {
    console.log(fp?.current?.value);
  }

Please englight me about this.

olmpazwi

olmpazwi1#

要在单击按钮时从React Flatpickr组件获取值,需要使用Flatpickr提供的onChange prop。
请检查下面的代码库。

import { useState, useRef } from "react";
import Flatpickr from "react-flatpickr";

function YourComponent() {
  const [selectedDateTime, setSelectedDateTime] = useState(null);
  const fp = useRef(null);

  // Function to handle the date/time selection change
  const handleDateTimeChange = (selectedDates) => {
    setSelectedDateTime(selectedDates[0]);
  };

  function handleSubmitAgenda() {
    console.log(selectedDateTime); // This will log the selected date/time when the button is clicked
  }

  return (
    <div>
      <Flatpickr
        ref={fp}
        name="startTime"
        className="py-2 bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-700 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500"
        options={{
          enableTime: true,
          noCalendar: true,
          dateFormat: "H:i",
        }}
        onChange={handleDateTimeChange} // Call handleDateTimeChange on date/time selection change
      />

      <button onClick={handleSubmitAgenda}>Submit</button>
    </div>
  );
}

字符串
我希望这对你有帮助。最好了

相关问题