首页 > 解决方案 > Typescript + React - 没有重载匹配这个调用

问题描述

我对 React + Typescript 有点陌生,我正在尝试根据它们的值来更新我创建的四个计数器。如您所见,每个计数器都有一个键,该键连接到它们在数组中的 id。

但是,当我尝试添加:value={counter.value}以便该值将更新并且每次都不会从零开始时,我会收到以下消息:

" No overload matches this call.
  Overload 1 of 2, '(props: Readonly<{}>): Counter', gave the following error.
    Type '{ key: number; value: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Counter> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
      Property 'value' does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes<Counter> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'.
  Overload 2 of 2, '(props: {}, context?: any): Counter', gave the following error.
    Type '{ key: number; value: number; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<Counter> & Readonly<{}> & Readonly<{ children?: ReactNode; }>'. "

我知道已经回答了一个与此非常相似的问题,但我真的不明白答案或如何解决它。先感谢您!

import * as React from "react";
import { Component } from "react";
import Counter from "./Hello";

class Counters extends Component {
  state = {
    counters: [
      { id: 1, value: 4 },
      { id: 2, value: 0 },
      { id: 3, value: 0 },
      { id: 4, value: 0 }
    ]
  };
  render() {
    return (
      <div>
        {this.state.counters.map(counter => (
          <Counter key={counter.id} value={counter.value} />
        ))}
      </div>
    );
  }
}

export default Counters;

下面是 Counter 组件:

    import * as React from 'react';


export default class Counter extends React.Component {
    state = {
        count: 0,
        tags: [] as number[]
    };

    renderTags() {
        if (this.state.tags.length === 0) return <p>There are no tags</p>

        return(
            <ul>
                {this.state.tags.map(tag => <li key={tag}>{tag}</li>)}
            </ul>
        )
    }

    handleIncrement = (product:any) =>{
        this.setState({ count: this.state.count +1 })
        console.log("increment clicked", this.state.count);

    }

    doHandleIncrement = () => {
        this.handleIncrement({id:1});
    }

    render() { 

        return (

        <div>
            <span style={this.styles} className={this.getClassName()}>{this.formatCount()}</span>
            <button onClick={this.doHandleIncrement}>Test</button>
        </div>
        );
    }

    private getClassName() {
        let classes = "state";
        classes += (this.state.count === 0) ? "Warning" : "Normal";
        return classes;
    }

    private formatCount() {
        const {count} = this.state;
        return count === 0 ? "Zero" : count
    }
};

标签: reactjstypescriptkey

解决方案


在 tsx 中,props 的类型(不要与 propTypes 混淆)需要在扩展 React.Component 时显式定义,否则类型{}将被假定为 props。

React.Component<Props = {}, State = {}>

因此,

export default class Counter extends React.Component<{ value:number }>{ ... }

是必需的,以便Counter组件通过value属性传递

<Counter value={4} />

keyprops 不是必需的,因为它已经作为可选属性内置到 React.Components


推荐阅读