gpt4 book ai didi

reactjs - Typescript + React - 没有重载匹配这个调用

转载 作者:行者123 更新时间:2023-12-05 02:08:51 24 4
gpt4 key购买 nike

我是 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
}
};

最佳答案

在 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 Prop 不是必需的,因为它已经作为 React.Components 的可选属性内置

关于reactjs - Typescript + React - 没有重载匹配这个调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60490456/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com