TS2339:“FC<ButtonProps>”类型上不存在属性“whyDidYouRender”

non*_*one 4 typescript reactjs

也许一个愚蠢的问题,但为什么这个错误 TS2339?!

import * as React from 'react';

import StyledButton from './Button.styled';

interface ButtonProps {
    label?: String;
    onClick?: (e: React.SyntheticEvent) => any | Function;
    whyDidYouRender?: any;
}

const Button: React.FC<ButtonProps> = (props: ButtonProps) => {
    return (
        <StyledButton onClick={props.onClick}>
            {props.label}
        </StyledButton>
    )
};
Button.whyDidYouRender = true;

export default Button;
Run Code Online (Sandbox Code Playgroud)

这一行的错误: Button.whyDidYouRender = true;

我该如何解决这个问题??

Tri*_*lay 9

编辑:

现在我了解了您的用例,这是一个更简单的答案。将您执行任务的行更改为

(Button as any).whyDidYouRender = true
Run Code Online (Sandbox Code Playgroud)

这将让您设置一次属性,否则将其视为常规功能组件。

原答案:

您试图将 Button 函数视为具有 type Button: ButtonProps,但 Button 被声明为Button: React.FC<ButtonProps>

FC<ButtonProps 是简称

(props: ButtonProps) => React.Node
// (this is slightly simplified)
Run Code Online (Sandbox Code Playgroud)

这意味着它是一个函数,它接受一个 props 类型的对象ButtonProps并返回一个 React 节点(粗略地说,一个 html 元素的表示,如按钮)。

因此,在函数体内,您可以访问props.labeland props.onClick,您可以这样做。您还可以props.whyDidYouRender在函数体内访问。

您犯的错误是这些属性存在于参数上props,而不是Button函数上。

const Button: React.FC<ButtonProps> = (props: ButtonProps) => {
    return (
        <StyledButton onClick={props.onClick}>
            {props.label}
            // You can do this, because props: ButtonProps
            {props.whyDidYouRender}
        </StyledButton>
    )
};
// FC<ButtonProps> doesn't have a whyDidYouRender property, so this fails.
Button.whyDidYouRender = true;
Run Code Online (Sandbox Code Playgroud)

如果你想whyDidYouRender在函数内部访问,你应该将它作为一个 prop 传入。

如果您真的希望分配Button.whyDidYouRender = true成功,则可以更改Button.

Button: React.FC<ButtonProps> & {whyDidYouRender: any} = (props) => ...
Run Code Online (Sandbox Code Playgroud)

这可能不是你真正想要做的,但从这个例子中并不清楚你想要完成什么,所以这是我能做的最好的。


小智 5

添加react-app-env.d.ts像这样的引用解决了问题:

/// <reference types="react-scripts" />
/// <reference types="@welldone-software/why-did-you-render" />
Run Code Online (Sandbox Code Playgroud)