6

使用此代码时出现错误Property 'type' does not exist on type 'EventTarget'。对于checked,value和 也是如此name

按照代码,我可以看到FormEvent从 that 继承SyntheticEvent的又具有target: EventTarget. EventTarget 没有我想要的属性。如果我将其标记eventany( 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)} />
4

1 回答 1

10

像这样解决它:

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" />
于 2017-06-26T11:04:46.837 回答