我是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;
以下是“计数器”组件:
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
}
};
答案 0 :(得分:2)
在tsx中,在扩展React.Component时,必须明确定义props的类型(不要与propTypes混淆),否则将假设类型{}
作为props。
React.Component<Props = {}, State = {}>
因此
export default class Counter extends React.Component<{ value:number }>{ ... }
是必需的,以便Counter
属性传递value
组件
<Counter value={4} />
key
道具不是必需的,因为它已经作为React.Components的可选属性内置