React TypeScript 2.3 -> 类型安全 React Bootstrap FormControl onChange
React TypeScript 2.3 -> typesafe React Bootstrap FormControl onChange
使用此代码时出现错误 Property 'type' does not exist on type 'EventTarget'
。 checked
、value
和 name
.
也是如此
根据代码,我可以看到 FormEvent
继承自 SyntheticEvent
,而 SyntheticEvent
又具有 target: EventTarget
。 EventTarget 没有我想要的属性。如果我改为将 event
标记为 any
(event: any
),则代码可以完美运行。我怎样才能解决这个问题?我尝试使用正常的 Html 输入,然后将事件设置为 React.ChangeEvent<HTMLInputElement>
.
handleChange(event: React.FormEvent<React.Component<ReactBootstrap.FormControlProps, {}>>) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
...
<FormGroup controlId="Email">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event)} placeholder="Email" />
</Col>
</FormGroup>
使用输入的工作代码:
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
...
}
...
<input
name="email"
type="email"
value={this.state.email}
onChange={(event) => this.handleChange(event)} />
这样解决的:
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name as any;
this.setState({
[name]: value
});
}
...
<FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event as any)} placeholder="Email" />
使用此代码时出现错误 Property 'type' does not exist on type 'EventTarget'
。 checked
、value
和 name
.
根据代码,我可以看到 FormEvent
继承自 SyntheticEvent
,而 SyntheticEvent
又具有 target: EventTarget
。 EventTarget 没有我想要的属性。如果我改为将 event
标记为 any
(event: any
),则代码可以完美运行。我怎样才能解决这个问题?我尝试使用正常的 Html 输入,然后将事件设置为 React.ChangeEvent<HTMLInputElement>
.
handleChange(event: React.FormEvent<React.Component<ReactBootstrap.FormControlProps, {}>>) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
...
<FormGroup controlId="Email">
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event)} placeholder="Email" />
</Col>
</FormGroup>
使用输入的工作代码:
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
...
}
...
<input
name="email"
type="email"
value={this.state.email}
onChange={(event) => this.handleChange(event)} />
这样解决的:
handleChange(event: React.ChangeEvent<HTMLInputElement>) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name as any;
this.setState({
[name]: value
});
}
...
<FormControl name="email" type="email" value={this.state.email} onChange={(event) => this.handleChange(event as any)} placeholder="Email" />