reactjs - TS2339 : Property 'whyDidYouRender' does not exist on type 'FC<ButtonProps>'

标签 reactjs typescript

也许一个愚蠢的问题,但为什么这个错误 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;

此行的错误:Button.whyDidYouRender = true;
我该如何解决这个问题??

最佳答案

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

(Button as any).whyDidYouRender = true
这将让您设置一次属性,否则将其视为常规功能组件。
原答案:
您试图将函数 Button 视为具有类型 Button: ButtonProps ,但 Button 被声明为 Button: React.FC<ButtonProps> .FC<ButtonProps是简称
(props: ButtonProps) => React.Node
// (this is slightly simplified)
这意味着它是一个接受类型为 ButtonProps 的 props 对象的函数并返回一个 React 节点(粗略地说,是一个 html 元素的表示,如按钮)。
因此,在函数体内部,您可以访问 props.labelprops.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;
如果您想访问 whyDidYouRender在函数内部,您应该将其作为 Prop 传递。
如果你真的想要这个任务 Button.whyDidYouRender = true要成功,您可以更改 Button 的类型.
Button: React.FC<ButtonProps> & {whyDidYouRender: any} = (props) => ...
这可能不是你真正想要做的,但从这个例子中并不清楚你想要完成什么,所以这是我能做的最好的。

关于reactjs - TS2339 : Property 'whyDidYouRender' does not exist on type 'FC<ButtonProps>' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58867121/

相关文章:

arrays - React - useState Hook 与 Context Api - 无法将状态数组复制到另一个状态数组

javascript - 将 ref 与 React.createElement 一起使用

javascript - 如何使用 Babel 为 Internet Explorer 11 构建 React 应用程序?

javascript - 有没有办法为 Jasmine 单元测试(Angular 4)提供基类?

reactjs - TS2531 : Object possibly 'null'

reactjs - 与简单地从商店配置中导出调度相比,useDispatch 有什么优势?

javascript - 如何显示作为 props 传递给功能组件的数组元素?

javascript - 将 observable 数组的 observable 转换为 observable 数组

typescript - 如何从现有的 JavaScript 库生成 .d.ts "typings"定义文件?

angular - 为什么 vs19 中的断点在 angular 8 更新后停止工作?