【问题标题】:Error: Cannot invoke an object which is possibly 'undefined'. for default prop is defined错误:无法调用可能是“未定义”的对象。为默认道具定义
【发布时间】:2018-12-10 02:09:33
【问题描述】:

我已经将 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;
                                    ^^^^^^^^
    }
}

无法调用可能是“未定义”的对象。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    一个肮脏的黑客,但它有效:(() =&gt; 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;
        }
    }
    

    【讨论】:

      【解决方案2】:
      猜你喜欢
      • 2020-10-02
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-14
      • 2019-11-16
      • 1970-01-01
      • 2021-08-07
      相关资源
      最近更新 更多