在我的react和typescript应用程序中,我使用:

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

我如何正确地定义类的类型,这样我就不必用任何类型系统来破解我的方法?

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'.

当前回答

您可以执行以下操作:

import { ChangeEvent } from 'react';

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

其他回答

import { NativeSyntheticEvent, TextInputChangeEventData,} from 'react-native';



  // Todo in java script
 const onChangeTextPassword = (text : any) => {
    setPassword(text);
  }
    

// Todo在类型脚本中使用这个

  const onChangeTextEmail = ({ nativeEvent: { text },}: NativeSyntheticEvent<TextInputChangeEventData>) => {
    console.log("________ onChangeTextEmail _________ "+ text);
    setEmailId(text);
  };


 <TextInput
          style={{ width: '100%', borderBottomWidth: 1, borderBottomColor: 'grey', height: 40, }}
          autoCapitalize="none"
          returnKeyType="next"
          maxLength={50}
          secureTextEntry={false}
          onChange={onChangeTextEmail}
          value={emailId}
          defaultValue={emailId}
          
        />

  
const handleChange = (
    e: ChangeEvent<HTMLInputElement>
  ) => {
    const { name, value } = e.target;
    this.setState({ ...currentState, [name]: value });
  };

您可以将此应用于表单组件中的每个输入元素

你试图在InputProps中添加的目标和你想要在React中添加的目标不一样。FormEvent

所以,我能想出的解决方案是,扩展事件相关的类型来添加你的目标类型,如下:

interface MyEventTarget extends EventTarget {
    value: string
}

interface MyFormEvent<T> extends React.FormEvent<T> {
    target: MyEventTarget
}

interface InputProps extends React.HTMLProps<Input> {
    onChange?: React.EventHandler<MyFormEvent<Input>>;
}

有了这些类之后,就可以使用输入组件as了

<Input onChange={e => alert(e.target.value)} />

没有编译错误。事实上,您还可以将上面的前两个接口用于其他组件。

由于@haind

是的HTMLInputElement为输入字段工作

//Example
var elem = e.currentTarget as HTMLInputElement;
elem.setAttribute('my-attribute','my value');
elem.value='5';

这个htmllinputelement的接口是继承自HTMLElement的,而HTMLElement是继承自根级别的EventTarget的。因此,我们可以根据上下文断言使用作为操作符来使用特定的接口,比如在这种情况下,我们使用HTMLInputElement作为输入字段,其他接口可以是HTMLButtonElement, HTMLImageElement等。

更多的参考,你可以检查其他可用的接口在这里

Mozilla的Web API接口 微软提供的外部节点模块接口

这也适用于我,它是框架不可知论者。

const handler = (evt: Event) => {
  console.log((evt.target as HTMLInputElement).value))
}