我有一个负责日期时间选择器的组件。我希望另一个父组件调用这个子日期选择器组件,这样我就可以拥有一个“包装器/容器”组件,一个仅用于数据选择器。此外,我在typescript上这样做没有成功。
这是我的代码沙箱:https ://codesandbox.io/s/date-picker-ubosl?file=/src/App.tsx
这是我的代码,该函数handleChangeDateType
最后执行一个 console.log() ,结果应该传递给 Parent 组件。
import React, { useState } from "react";
import { DatePicker, MuiPickersUtilsProvider } from "@material-ui/pickers";
import ReactSelect, { ValueType } from "react-select";
import DateFnsUtils from "@date-io/date-fns";
export enum DateValueEnum {
Today = "TODAY",
Yesterday = "YESTERDAY",
Custom = "CUSTOM"
}
type OptionType = {
key: string;
label: string;
};
const options: OptionType[] = [
{ key: DateValueEnum.Today, label: "Today" },
{ key: DateValueEnum.Yesterday, label: "Yesterday" },
{ key: DateValueEnum.Custom, label: "Custom" }
];
export default function App() {
const [selectedDate, setSelectedDate] = React.useState<Date | null>(
new Date()
);
const [selectedOption, setSelectedOption] = useState<ValueType<OptionType>>();
const handleChangeDateType = (value: string) => {
let startDate: Date | undefined = undefined;
let endDate: Date | undefined = undefined;
const startToday = new Date();
switch (value) {
case DateValueEnum.Today: {
startDate = startToday;
endDate = new Date(startDate.getTime());
break;
}
case DateValueEnum.Yesterday: {
startDate = new Date(startToday.getTime());
startDate.setDate(startDate.getDate() - 1);
endDate = new Date(startDate.getTime());
break;
}
default: /** nothing */
}
console.log(startDate);
console.log(endDate);
};
const handleChange = (option: ValueType<OptionType>) => {
setSelectedOption(option.key);
handleChangeDateType(option.key);
};
return (
<div className="App">
<div>
<ReactSelect
value={selectedOption as ValueType<OptionType>}
onChange={(option) => handleChange(option)}
isMulti={false}
options={options}
/>
{selectedOption === DateValueEnum.Custom ? (
<div style={{ display: "flex" }}>
<div style={{ width: "50%", float: "left", paddingRight: "5px" }}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker
fullWidth
margin="normal"
required={true}
error={false}
invalidLabel={"Several values..."}
value={selectedDate}
onChange={(newDate) => setSelectedDate(newDate)}
format="MM/dd/yyyy"
/>
</MuiPickersUtilsProvider>
</div>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<DatePicker
fullWidth
margin="normal"
required={true}
error={false}
invalidLabel={"Several values..."}
value={selectedDate}
onChange={(newDate) => setSelectedDate(newDate)}
format="MM/dd/yyyy"
/>
</MuiPickersUtilsProvider>
</div>
) : null}
</div>
</div>
);
}