打字稿输入 onchange event.target.value

新手上路,请多包涵

在我的反应和打字稿应用程序中,我使用:

onChange={(e) => data.motto = (e.target as any).value}

我如何正确定义类的类型,这样我就不必用 any 来破解类型系统了?

export interface InputProps extends React.HTMLProps<Input> {
...

}

export class Input extends React.Component<InputProps, {}> {
}

如果我把 target: { value: string }; 我得到:

ERROR in [default] /react-onsenui.d.ts:87:18
Interface 'InputProps' incorrectly extends interface 'HTMLProps<Input>'.
  Types of property 'target' are incompatible.
    Type '{ value: string; }' is not assignable to type 'string'.

原文由 wildeyes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 530
2 个回答

通常事件处理程序应该使用 e.currentTarget.value ,例如:

onChange = (e: React.FormEvent<HTMLInputElement>) => {
    const newValue = e.currentTarget.value;
}

你可以在这里阅读为什么会这样( Revert “Make SyntheticEvent.target generic, not SyntheticEvent.currentTarget.” )。

UPD:正如@roger-gusmao ChangeEvent 所述,更适合输入表单事件。

onChange = (e: React.ChangeEvent<HTMLInputElement>)=> {
   const newValue = e.target.value;
}

原文由 Yozi 发布,翻译遵循 CC BY-SA 4.0 许可协议

在 TypeScript 中使用的正确方法是

  handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    // No longer need to cast to any - hooray for react!
    this.setState({temperature: e.target.value});
  }

  render() {
        ...
        <input value={temperature} onChange={this.handleChange} />
        ...
    );
  }

跟着完整的课,更好理解:

 import * as React from "react";

const scaleNames = {
  c: 'Celsius',
  f: 'Fahrenheit'
};

interface TemperatureState {
   temperature: string;
}

interface TemperatureProps {
   scale: string;

}

class TemperatureInput extends React.Component<TemperatureProps, TemperatureState> {
  constructor(props: TemperatureProps) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
    this.state = {temperature: ''};
  }

  //  handleChange(e: { target: { value: string; }; }) {
  //    this.setState({temperature: e.target.value});
  //  }

  handleChange(e: React.ChangeEvent<HTMLInputElement>) {
    // No longer need to cast to any - hooray for react!
    this.setState({temperature: e.target.value});
  }

  render() {
    const temperature = this.state.temperature;
    const scale = this.props.scale;
    return (
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature} onChange={this.handleChange} />
      </fieldset>
    );
  }
}

export default TemperatureInput;

原文由 Roger Gusmao 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进