在react-native-paper-dates中选择多个日期并再次显示DatePickerModal后,使用multiple时未定义不起作用

dwbf0jvd  于 2023-03-31  发布在  React
关注(0)|答案(1)|浏览(130)

错误“undefined is not function”when using multiple,after select multi dates and show DatePickerModal again. Im using“react-native-paper-dates”

const [showDate, setShowDate] = useState(false);
  const [dates, setDates] = useState<any>([]);

  <DatePickerModal
    locale="en"
    mode="multiple"
    visible={showDate}
    onDismiss={() => setShowDate(false)}
    dates={dates}
    onConfirm={dates => {
      console.log(dates);
      setShowDate(false);
      setDates(dates);
    }}
  />

下面是我的完整代码:我不知道如何修复,因为它发生在图书馆“React-本土-论文日期”。任何人都可以帮助我。非常感谢
我通过为DatePickerModal添加2个useCallback函数onDismiss和onConfirm来修复它!

const onDismiss = useCallback(() => {
    setShowDate(false);
  }, [setShowDate]);

  const onConfirm = useCallback((params: any) => {
    setShowDate(false);
    setDates(params.dates);
  }, []);
oipij1gg

oipij1gg1#

react-native-paper-dates documentation中看不太清楚,但它传递给onConfirm回调函数的值是一个包含.dates的结构,而不仅仅是一个日期数组:

export type MultiConfirm = (params: { dates: Date[] }) => void

您现有的onConfirm回调只需要做一点更改:

onConfirm={params => {
      console.log(params);
      setShowDate(false);
      setDates(params.dates);
    }}

Typescript实际上可以发现这种类型的问题-而不是调用useState<any>,您可以指定预期的类型:

const [dates, setDates] = useState<Date[]>([]);

指定此更强的类型后,Typescript会在原始回调上显示错误:

Argument of type '{ dates: Date[]; }' is not assignable to parameter of type 'SetStateAction<Date[]>'.

相关问题