KeyBoardDatePicker组件,Material-ui / pickers,Typescript中的labelFunc中的类型错误

时间:2020-07-27 17:18:31

标签: reactjs typescript material-ui

我有这个Material-ui Pickers组件:

<KeyboardDatePicker
   value={selectedDate}
   onChange={(_, newValue) => handleClick(newValue)}
   labelFunc={renderLabel}
   disableToolbar
   variant='inline'
   inputVariant='filled'
   format='YYYYMMDD'
   autoOk
 />

renderLabel函数在哪里:

const renderLabel = (date: string | null) => date === null ? 'placeholder' : momen(date).format(YYYYMMDD)string

这是我得到的错误:

Type '(date: string | null) => string' is not assignable to type '(date: MaterialUiPickersDate, invalidLabel: string) => string'.
 Types of parameters 'date' and 'date' are incompatible.
   Type 'MaterialUiPickersDate' is not assignable to type 'string | null'.
     Type 'Moment' is not assignable to type 'string'.ts(2322)

我也尝试导入Moment并像这样使用它:

const renderLabel = (date: Moment) => date === null ? 'placeholder' : momen(date).format(YYYYMMDD)string

它仍然会给出编译器错误。 我应该为labelFunc使用哪种类型?

2 个答案:

答案 0 :(得分:1)

错误是不言自明的。

该组件希望给您一个MaterialUiPickersDate,而您的函数接受一个string。他们不匹配。

将功能更改为接受MaterialUiPickersDate,它将不再抱怨。

答案 1 :(得分:0)

这与纯Date完美配合:

renderLabel: (date: Date|null, invalidLabel: string) => string

完整示例:

import React from 'react';
import { KeyboardDatePicker } from '@material-ui/pickers'

type MyComponentProps = {
    selectedDate: string;
    renderLabel: (date: Date|null, invalidLabel: string) => string
    handleClick: (v: string | null | undefined) => null
}

const MyComponent: React.FC<MyComponentProps> = ({ selectedDate, renderLabel, handleClick }) => (<KeyboardDatePicker
    value={selectedDate}
    onChange={(_, newValue) => handleClick(newValue)}
    labelFunc={renderLabel}
    disableToolbar
    variant='inline'
    inputVariant='filled'
    format='YYYYMMDD'
    autoOk
/>
)

export default MyComponent;

经过测试

"@material-ui/pickers": "^3.2.10",

更新日期为null,谢谢@ known-as-bmf!