簡體   English   中英

React + Typescript:類型*中缺少屬性*

[英]React + Typescript: Property * is missing in type *

我正在嘗試通過React Tutorial ,但是發生了一個我不明白的錯誤。

錯誤消息是:

comment.tsx(30,5): error TS2324: Property 'data' is missing in type 'MyProps'.
comment.tsx(31,5): error TS2324: Property 'data' is missing in type 'MyProps'.
main.tsx(20,17): error TS2324: Property 'author' is missing in type 'MyProps'.
main.tsx(27,18): error TS2324: Property 'author' is missing in type 'MyProps'.

這是main.tsx

import * as React from 'react';
import 'jquery';
import { CommentList, CommentForm, MyProps } from './comment';

var data = [
  {author: "Pete Hunt", text: "This is one comment"},
  {author: "Jordan Walke", text: "This is *another* comment"}
];

class CommentBox extends React.Component<MyProps, {}> {
    render() {
        return <div className="commentBox">
                <h1>Comments</h1>
                <CommentList data={this.props.data} />
                <CommentForm />
                </div>;
    }
}

$(() => {
    React.render(<CommentBox data={data} />, document.getElementById('content'));
});

並且comment.tsx

import * as React from 'react';

export interface MyProps extends React.Props<any> {
    author: string;
    data: Array<any>;
}

export class Comment extends React.Component<MyProps, {}> {
    render() {
        let rawMarkup = marked(this.props.children.toString(), {sanitize: true});
        return <div className="comment">
                 <h2 className="commentAuthor">
                   {this.props.author}
                 </h2>
                 <span dangerouslySetInnerHTML={{__html: rawMarkup}} />
               </div>;
    }
}

export class CommentList extends React.Component<MyProps, {}> {
    render() {
        return <div className="commentList">
                <Comment author="Pete Hunt">Some comment</Comment>
                <Comment author="Jordan Walke">Another *comment*</Comment>
                </div>;
    }
}

export class CommentForm extends React.Component<{}, {}> {
    render() {
        return <div className="commentForm">
               A CommentForm
               </div>;
    }
}

我記得讀過接口僅用於類型檢查,並且在轉換后的代碼中不存在。 但是,我仍然不完全理解為什么我會收到這些錯誤。

另外,我正在使用DefinitelyTyped中的類型定義。

comment.tsx(30,5):錯誤TS2324:“MyProps”類型中缺少屬性“數據”。 comment.tsx(31,5):錯誤TS2324:“MyProps”類型中缺少屬性“數據”。 main.tsx(20,17):錯誤TS2324:“MyProps”類型中缺少屬性“author”。 main.tsx(27,18):錯誤TS2324:“MyProps”類型中缺少屬性“author”。

你可能會混淆MyProps for CommentList (不包含.author )和MyProps for Comment (不包含.data )。

如果為這兩個組件使用不同的 Prop接口,則會更好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM