【问题标题】:ReactJS typescript error Parameter props implicitly has 'any' typeReactJS typescript error Parameter props隐含地具有'any'类型
【发布时间】:2018-08-23 02:52:55
【问题描述】:

按照教程 here 进行调整,我在尝试定义一个函数来呈现一些 HTML 时遇到了困难。

function Toolbar(props) {
    return (
        <div>
            <button onClick={() => props.onClick()}>Refresh</button>
        </div>
    );
}

Typescript 中出现此错误,因为未定义 props。我明白为什么我会收到错误,但我缺少的是 props 应该是什么类型?

我相信我应该能够在这样的另一个组件中使用它:

function App() {
    return (
        <div>
            <Toolbar onClick={() => alert('hello world')}>Test</Toolbar>
        </div>
    );
}

props 就是我指定的任何内容。这似乎得到了证实here:尽管该链接没有提到打字稿。所以,我的问题是:这个特性(将属性传递给函数或类的特性)如何与打字稿一起使用,根据定义,你不知道你正在传递什么?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    你应该为道具定义一个接口。

    interface Props {
       onClick: () => void;
    }
    
    function Toolbar(props: Props) {
       return (
           <div>
               <button onClick={() => props.onClick()}>Refresh</button>
           </div>
       );
    }
    

    我还喜欢将我的函数组件定义为箭头函数。您可以将 FC(功能组件)类型定义与 Props 泛型类型一起使用。这样您就可以立即解构您的属性。

    const Toolbar: React.FC<Props> = ({onClick}) => {
       return (
           <div>
               <button onClick={() => onClick()}>Refresh</button>
           </div>
       );
    }
    

    【讨论】:

    • 如果props 只是一个属性字典呢?例如{width, height, id} 这个有类型吗?
    • @Anthony Kong,您可以以相同的方式使用它们。使用提到的属性名称及其相应的类型设置一个接口。 interface Props { width: number, heights: number, id: string }
    猜你喜欢
    • 2019-08-04
    • 1970-01-01
    • 2017-11-30
    • 1970-01-01
    • 2020-12-17
    • 2019-03-15
    • 2021-12-11
    • 1970-01-01
    • 2021-11-23
    相关资源
    最近更新 更多