在 React 中从".js"切换到".tsx"后,类型 'ReadOnly <{}>' 上不存在属性



从JavaScript切换到TypeScript后,我得到错误:

类型'ReadOnly<上不存在属性;{}>'

在此代码中:

this.state.flashcards

似乎我需要将flashcards定义为一种类型,但当我将flashcards: []更改为flashcards: any[]时,会出现一个错误,即任何值都被用作值。

我如何才能像在JavaScript中那样在TypeScript中编译它?

import React from 'react';
import Flashcard from './Flashcard';
const flashcards = require('../data/custom/itemType_flashcards.json');
class Main extends React.Component {
constructor(props: any) {
super(props);
this.state = {
flashcards: []
};
}
componentDidMount() {
this.setState({
flashcards
});
}
render() {
return (
<div className="content">
{this.state.flashcards.map(flashcard => <Flashcard {...flashcard} key={flashcard.id} />)}
</div>
);
}
}
export default Main;

使用typescript时,React.Component是一个泛型,您可以使用它来指定道具和状态的类型。如果你不这样做,默认情况下道具和状态是空对象,当你试图分配一个不是空对象的状态时,这会导致错误。因此,请执行以下操作:

interface MainState {
flashcards: FlashcardProps[]; // You'll need to define the shape of FlashcardProps too
}
class Main extends React.Component<{}, MainState> {
// The rest is unchanged
}

相关内容

最新更新