我想利用 TypeScript 中的静态和强类型,但仅限于状态,因为我不打算采用任何props。
当我尝试这样传递接口时,我最终遇到了一个错误:
import * as React from 'react';
import {Link} from 'react-router-dom';
import Constants from '../Constants';
interface ILoginState {
email: string;
password: string;
remember: boolean;
error: string;
isLoading: boolean;
}
class LoginView extends React.Component<{}, ILoginState> {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
remember: false,
error: '',
isLoading: false
};
}
render() {
return (<div>Login goes here</div>
);
}
}
export default LoginView;
我最终得到一个编译错误:
ERROR in [at-loader] ./src/scripts/pages/LoginView.tsx:41:21
TS2345: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type 'ILoginState | ((prevState: Readonly<ILoginState>, props: {}) => ILoginState | Pick<ILoginState, "...'.
Type '{ [x: number]: any; }' is not assignable to type 'Pick<ILoginState, "email" | "password" | "remember" | "error" | "isLoading">'.
Property 'email' is missing in type '{ [x: number]: any; }'.
我也试过用 'any' 代替空括号,但这也不起作用。
这是跟踪所指的第 41 行(this.SetState...):
handleChange = event => {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
[target.name]: value
});
}
以下是使用它的所有示例:
<input name="email" type="email" value={this.state.email} onChange={this.handleChange} />
<input name="password" type="password" value={this.state.password} onChange={this.handleChange} />
<input name="remember" type="checkbox" checked={this.state.remember} onChange={this.handleChange} />