gpt4 book ai didi

reactjs - typescript 将 setState 与用户输入 react

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:32 25 4
gpt4 key购买 nike

在这个 typescript react (create-react-app) 的基本示例中,我试图通过用户输入更改 state.name。

谁能告诉我一个工作示例(我没有找到)或更好的示例:文档在哪里?

linter 的(第二个)错误是:

(54,24): error TS2322: Type '{ onChange: (e: Event) => void; }' is not assignable to type 'DetailedHTMLProps, HTMLInputElement>'. Type '{ onChange: (e: Event) => void; }' is not assignable to type 'InputHTMLAttributes'. Types of property 'onChange' are incompatible. Type '(e: Event) => void' is not assignable to type 'EventHandler> | undefined'. Type '(e: Event) => void' is not assignable to type 'EventHandler>'. Types of parameters 'e' and 'event' are incompatible. Type 'ChangeEvent' is not assignable to type 'Event'. Property 'cancelBubble' is missing in type 'ChangeEvent'.

import * as React from 'react';
import './Hello.css';

interface Props {
name: string;
}

interface State {
name: string;
}

class Hello extends React.Component<Props, State> {

public static defaultProps = {
name: 'John',
};

constructor(props: Props) {
super(props);
this.state = {
name: props.name,
};
this.handleChange = this.handleChange.bind(this);
}

handleChange(e: Event): void {
this.setState({
name: e.target.value //Error : property 'value' does not exist on type 'EventTarget'
});
}

render(): JSX.Element {
return (
<div className="hello">
Hello {this.state.name}
<input onChange={(e: Event) => this.handleChange(e)} /> //error is at this line
</div>
);
}
}

export default Hello;

最佳答案

改变你的

handleChange(e: Event)

handleChange (e: React.FormEvent<HTMLInputElement>)

e.target.name;

e.currentTarget.name;

另外,你可能想改变

 <input onChange={(e: Event) => this.handleChange(e)} />

 <input onChange={this.handleChange} />

关于reactjs - typescript 将 setState 与用户输入 react ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46666036/

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