![](/img/trans.png)
[英]error TS2339: Property 'items' does not exist on type 'Readonly<{}>'
[英]Property does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339
在嘗試將文件轉換為 typescript 時,出現上述錯誤
handleToggle() {
const { toggleTodo, id } = this.props; // <-- Error
toggleTodo(id);
}
我已經嘗試了幾種方法,例如向我為此組件添加的接口添加屬性、添加綁定語句、為這些屬性添加方法等。但是它們都會給出錯誤,通常是上述錯誤。 只是添加 typescript 檢查似乎我不需要做很多改變。 我在這里看到的其他類似問題和答案沒有幫助。 例如,我將這些項目添加到界面道具中,但仍然出現錯誤。
到目前為止我的代碼(在轉換之前工作正常)是
import React, { Component } from 'react'
interface TodoItemProps { // Added this interface for props
title: string,
completed: boolean,
}
export default class TodoItem extends Component {
constructor(props:TodoItemProps) { // used inteface from abovereact
super(props);
this.handleToggle = this.handleToggle.bind(this);
this.handleRemove = this.handleRemove.bind(this);
}
handleToggle() {
const { toggleTodo, id } = this.props; // < -- errors here.
toggleTodo(id);
}
handleRemove() {
const { removeTodo, id } = this.props;
removeTodo(id);
}
render() {
const { title, completed } = this.props;
return (
<div style={{ width: 400, height: 25 }} >
<input
type="checkbox"
checked={completed}
onChange={this.handleToggle} />
{title}
<button style={{ float: 'right' }} onClick={this.handleRemove}>x</button>
</div>
)
}
}
我有
@types/react
@types/react-node
作為開發依賴。
不知道如何解決這個問題
目前,您還沒有告訴 typescript 這個組件需要什么道具,所以它默認為空 object {}
。 您確實在構造函數中放置了一個類型,但這不是將其應用於整個 class 的正確位置。
要修復它,請更改此:
export default class TodoItem extends Component {
對此:
export default class TodoItem extends Component<TodoItemProps> {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.