[英]Get accurate value onChange event in react.js
I'm trying to get the value of the date onChange:我正在尝试获取日期 onChange 的值:
<Flatpickr
data-enable-time
name="goodsreadyby"
options={{
minDate: date,
enableTime: true,
dateFormat:
'Y-m-d H:i:s'
}}
onChange={(date) => {setGoodsReadyBy({date})
}}/>
My problem is that I'm getting Array onChange event.我的问题是我收到 Array onChange 事件。 Currently:
现在:
{date: Array(1)}
date: Array(1)
0: Sat Mar 05 2022 16:20:00 (Some Standard Time)
[[Prototype]]: Object
length: 1
[[Prototype]]: Array(0)
[[Prototype]]: Object
But I need the value like Sat Mar 05 2022 16:20:00 (Some Standard Time)
only.但我只需要像
Sat Mar 05 2022 16:20:00 (Some Standard Time)
这样的值。 How did I modify my code to get the exact value that I needed.我如何修改我的代码以获得我需要的确切值。
The 1st param of Flatpickr's onChange
prop is selectedDates
- an array of Dates (you can just access the first with selectedDates[0]
and format it like you would with any Date). Flatpickr 的
onChange
属性的第一个参数是selectedDates
- 一组日期(您可以使用selectedDates[0]
访问第一个并像使用任何日期一样格式化它)。
The 2nd is the dateStr
- as formatted by the dateFormat
option.第二个是
dateStr
- 由dateFormat
选项格式化。
export default function App() {
return (
<Flatpickr
data-enable-time
name="goodsreadyby"
options={{
enableTime: true,
dateFormat: "Y-m-d H:i:s"
}}
onChange={(selectedDates, dateStr, instance) => {
const firstDate = selectedDates[0];
console.log({ firstDate, dateStr });
}}
/>
);
}
onChange will receive 3 arguments when called.
onChange 将在调用时收到 3 arguments。 These are:
这些都是:
selectedDates
- an array of Date objects selected by the user.selectedDates
- 用户选择的日期对象数组。 When there are no dates selected, the array is empty.当没有选择日期时,数组为空。
dateStr
- a string representation of the latest selected Date object by the user.dateStr
- 用户最近选择的日期 object 的字符串表示。 The string is formatted as per the dateFormat option.该字符串根据 dateFormat 选项进行格式化。
instance
- the flatpickr object, containing various methods and properties.instance
- flatpickr object,包含各种方法和属性。
You can print the date like,您可以像这样打印日期,
goodsReadyBy?.date[0].toString()
Code to fetch the date string alone:单独获取日期字符串的代码:
const App = () => {
const [goodsReadyBy, setGoodsReadyBy] = useState();
return (
<div>
<Flatpickr
data-enable-time
name="goodsreadyby"
options={{
enableTime: true,
dateFormat: "Y-m-d H:i:s"
}}
onChange={(date) => {
setGoodsReadyBy({ date });
}}
/>
<p> {goodsReadyBy?.date[0].toString()} </p>
</div>
);
};
Codesandbox:代码沙盒:
Well your array only has one element so you can use the code below.那么你的数组只有一个元素,所以你可以使用下面的代码。
onChange={(date) => {setGoodsReadyBy({date[0]})
It will give you the data in the format you need.它将以您需要的格式为您提供数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.