I have been reading the guidelines for handing multiple inputs in React.
https://facebook.github.io/react/docs/forms.html#handling-multiple-inputs
The code works but the problem starts with TypeScript. I get the following error for this.setState({ [name]: value});
:
error TS2345: Argument of type '{ [x: string]: string | boolean; }' is not assignable to parameter of type 'Pick<IState, "password" | "email">'. Property 'password' is missing in type '{ [x: string]: string | boolean; }
How can I fix this? I understand that [name]
is not matched against the state properties but I would like a good solution for it and not a hacking one.
Code:
interface IState {
email: string,
password: string
}
...
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
...
<input
name="email"
type="email"
value={this.state.email}
onChange={(event) => this.handleChange(event)} />
Try this:
const name = target.name as "password" | "email";
const newState: Partial<IState> = {};
newState[name] = value;
this.setState(newState);
决定暂时解决此问题:
const name = target.name as any;
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.