在我的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'.

当前回答

我们还可以使用onChange事件触发定义的类型(在函数组件中),如下所示:

 const handleChange = (
    e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
  ) => {
        const name = e.target.name;
        const value = e.target.value;
};

其他回答

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

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

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

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

您可以执行以下操作:

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

  

这是当你使用FileList对象的时候:

onChange={(event: React.ChangeEvent<HTMLInputElement>): void => {
  const fileListObj: FileList | null = event.target.files;
  if (Object.keys(fileListObj as Object).length > 3) {
    alert('Only three images pleaseeeee :)');
  } else {
    // Do something
  }

  return;
}}