reactjs - 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
}
};
解决方案
在 tsx 中,props 的类型(不要与 propTypes 混淆)需要在扩展 React.Component 时显式定义,否则类型{}
将被假定为 props。
React.Component<Props = {}, State = {}>
因此,
export default class Counter extends React.Component<{ value:number }>{ ... }
是必需的,以便Counter
组件通过value
属性传递
<Counter value={4} />
key
props 不是必需的,因为它已经作为可选属性内置到 React.Components
推荐阅读
- php - 错误:类 Illuminate\Database\Eloquent\Builder 的对象无法转换为字符串
- eclipse - 如何将 Eclipse IDE 与 Databricks 集群集成
- typescript - 类型 {} 上不存在属性 ID
- wiremock - Wiremock 独立的对象动态响应数组不适用于 bodyPatterns 和 matchesJsonPath
- javascript - 为 Chart.js 动态添加颜色
- javascript - 为什么幻灯片图片比屏幕(和容器)大?
- c# - 由于 luis api 异常错误,机器人无法正常工作
- google-bigquery - 在 Bigquery 中替换表分区中的数据
- http2 - WinHTTP over HTTP/2 多路复用
- mysql - 具有条件唯一的并发写入数据库