0

使用 forwardRef 和 office-ui-fabric 的 DatePicker 组件时出现错误。我正在尝试创建一个功能组件并返回对结构组件的引用。我的代码如下:

import React, { forwardRef } from "react";
import styled from "styled-components";
import { DatePicker, IDatePicker, IRefObject } from "office-ui-fabric-react";

interface IProps extends IDatePicker {
    label?: string;
    error?: string;
}

export const Date = forwardRef<IRefObject<IDatePicker>, IProps>(({ ...props }, ref) => {

    return <DateStyled>

        <DatePicker componentRef={ref} />

    </DateStyled>
});

const DateStyled = styled.div``;

我得到的错误在线

<DatePicker componentRef={ref} />

它说以下

Type '((instance: React.RefObject<IDatePicker> | RefObject<...> | ((ref: IDatePicker | null) => void) | null) => void) | MutableRefObject<...> | null' is not assignable to type 'React.RefObject<IDatePicker> | RefObject<...> | ((ref: IDatePicker | null) => void) | undefined'.
  Type 'null' is not assignable to type 'React.RefObject<IDatePicker> | RefObject<...> | ((ref: IDatePicker | null) => void) | undefined'.ts(2322)
DatePicker.types.d.ts(26, 5): The expected type comes from property 'componentRef' which is declared here on type 'IntrinsicAttributes & IDatePickerProps & { children?: ReactNode; }'

你能帮我弄清楚吗。非常感谢

4

1 回答 1

0

好吧,我想我已经找到了解决方案。我分享给有同样问题的人。

import React, { forwardRef } from "react";
import styled from "styled-components";
import { DatePicker, IDatePicker, IDatePickerProps } from "office-ui-fabric-react";

interface IProps extends IDatePickerProps {
    label?: string;
    error?: string;
}


export const Date = forwardRef<IDatePicker, IProps>(({ ...props }, ref) => {


    return <DateStyled>

        <DatePicker  {...props} componentRef={ref || undefined} />

    </DateStyled>
});

const DateStyled = styled.div``;
于 2020-06-24T15:28:13.403 回答