简体   繁体   中英

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.

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:

(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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM