[英]typescript react setState with user input
In this basic example of typescript react (create-react-app) I am trying to change the state.name by a user input.在这个 typescript react (create-react-app) 的基本示例中,我试图通过用户输入更改 state.name。
Could someone show me a working example (which I didn't found) or better: where the documentation is?有人可以给我一个工作示例(我没有找到)或更好的示例:文档在哪里?
The (second) error of the linter is: linter 的(第二个)错误是:
(54,24): error TS2322: Type '{ onChange: (e: Event) => void; (54,24): 错误 TS2322: 类型 '{ onChange: (e: Event) => void; }' is not assignable to type 'DetailedHTMLProps, HTMLInputElement>'. }' 不可分配给类型 'DetailedHTMLProps, HTMLInputElement>'。 Type '{ onChange: (e: Event) => void;输入 '{ onChange: (e: Event) => void; }' is not assignable to type 'InputHTMLAttributes'. }' 不可分配给类型 'InputHTMLAttributes'。 Types of property 'onChange' are incompatible.属性“onChange”的类型不兼容。 Type '(e: Event) => void' is not assignable to type 'EventHandler> |类型 '(e: Event) => void' 不可分配给类型 'EventHandler> | undefined'.不明确的'。 Type '(e: Event) => void' is not assignable to type 'EventHandler>'.类型“(e: Event) => void”不可分配给类型“EventHandler>”。 Types of parameters 'e' and 'event' are incompatible.参数“e”和“event”的类型不兼容。 Type 'ChangeEvent' is not assignable to type 'Event'.类型“ChangeEvent”不可分配给类型“Event”。 Property 'cancelBubble' is missing in type 'ChangeEvent'. “ChangeEvent”类型中缺少属性“cancelBubble”。
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;
Change your 改变你的
handleChange(e: Event)
with 同
handleChange (e: React.FormEvent<HTMLInputElement>)
and 和
e.target.name;
with 同
e.currentTarget.name;
Also, you may want to change 此外,您可能想要更改
<input onChange={(e: Event) => this.handleChange(e)} />
with 同
<input onChange={this.handleChange} />
Just do this:只需这样做:
handleChange = (event: Event) => {
const { value } = event.target as unknown as { value: string, };
this.setState({
...this.state,
name: value.trim()
});
};
<input type='text' onChange={this.handleChange} />
And the squeegee lines will go away.刮线将 go 移开。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.