私の React および TypeScript アプリでは、以下を使用します。
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'.
ベストアンサー1
一般的に、イベント ハンドラーは を使用する必要がありますe.currentTarget.value
。例:
const onChange = (e: React.FormEvent<HTMLInputElement>) => {
const newValue = e.currentTarget.value;
}
その理由については、こちらで読むことができます(「SyntheticEvent.currentTarget ではなく、SyntheticEvent.target を汎用化します。」を元に戻します。)。
UPD: @roger-gusmao が述べたように、ChangeEvent
フォーム イベントの入力に適しています。
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
}