【问题标题】:Property does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339类型 'Readonly<{}> & Readonly<{ children?: ReactNode; 上不存在属性}>'。 TS2339
【发布时间】:2020-11-07 18:44:02
【问题描述】:

在尝试将文件转换为打字稿时,出现上述错误

handleToggle() {
  const { toggleTodo, id } = this.props;    // <-- Error
  toggleTodo(id);
}

我尝试了几件事,例如向我为该组件添加的接口添加属性、添加绑定语句、为这些属性添加方法等。但是它们都会给出错误,通常是上述错误。只是添加打字稿检查似乎我不需要做很多改变。我在这里看到的其他类似问题和答案没有帮助。例如,我将这些项目添加到界面道具中,但仍然出现错误。

到目前为止我的代码(在此转换之前运行良好)是

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

作为开发依赖项。

不知道如何解决这个问题

【问题讨论】:

标签: reactjs react-proptypes


【解决方案1】:

目前,你还没有告诉 typescript 这个组件需要什么道具,所以它默认为一个空对象{}。您确实在构造函数中放置了一个类型,但这不是将其应用于整个类的正确位置。

要修复它,请更改:

export default class TodoItem extends Component {

到这里:

export default class TodoItem extends Component<TodoItemProps> {

【讨论】:

    猜你喜欢
    • 2020-01-24
    • 2019-12-11
    • 2020-11-29
    • 2018-10-11
    • 2018-10-14
    • 2019-02-14
    • 2021-08-10
    • 1970-01-01
    • 2020-09-20
    相关资源
    最近更新 更多