React TypeScript 2.3 - > typesafe React Bootstrap FormControl onChange

时间:2017-06-26 10:32:45

标签: javascript reactjs typescript react-bootstrap react-tsx

使用此代码时,我收到错误Property 'type' does not exist on type 'EventTarget'。同样适用于checkedvaluename

根据代码,我可以看到FormEvent继承自SyntheticEventtarget: EventTarget又有event。 EventTarget没有我追求的属性。如果我将any标记为event: anyReact.ChangeEvent<HTMLInputElement>),则代码可以完美无缺地运行。我怎样才能解决这个问题?我尝试使用普通的Html输入,然后将事件设置为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)} />

使用输入工作代码:

#!/bin/bash
java -jar /opt/AudiobookConverter/AudiobookConverter.jar "$@"

1 个答案:

答案 0 :(得分:2)

解决这个问题:

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" />