我已经将prop children
描述为可选,但它具有默认prop,甚至声明Typescript都会引发错误
import React, { MouseEvent } from 'react';
const defaultProps = {
children: () => null,
};
type TMouseCoordinates = { x: number, y: number };
type TProps = Partial<
{
children?: (coordinates: TMouseCoordinates) => JSX.Element | null;
} & TDefaultProps
>;
class MouseCoordinates extends React.Component<TProps, TState> {
static readonly defaultProps: TProps = defaultProps;
render() {
const { children } = this.props;
const isRenderIsFunction = typeof this.props.children === 'function';
return isRenderIsFunction ? children(this.state) : null;
^^^^^^^^
}
}
无法调用可能是“未定义”的对象。
答案 0 :(得分:2)
肮脏的骇客,但可以使用:(() => null) as TRenderCallback
import React, { MouseEvent } from 'react';
const defaultProps = {
children: (() => null) as TRenderCallback,
};
type TRenderCallback = (coordinates: TMouseCoordinates) => JSX.Element | null;
type TMouseCoordinates = { x: number, y: number };
type TProps = Partial<
{
children?: TRenderCallback;
} & typeof defaultProps
>;
class MouseCoordinates extends React.Component<TProps, TState> {
static readonly defaultProps: TProps = defaultProps;
render() {
const { children } = this.props;
const isRenderIsFunction = typeof this.props.children === 'function';
return isRenderIsFunction ? children(this.state) : null;
}
}
答案 1 :(得分:0)
在Typescript 3.0中添加了对defaultProps
的支持:https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-0.html#support-for-defaultprops-in-jsx