没有道具的TypeScript React State

时间:2018-06-04 23:57:13

标签: reactjs typescript

我想利用TypeScript中的静态和强类型,但仅限于状态,因为我不打算接受任何道具。

当我尝试传递接口时,我最终得到一个错误:

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

我也试过使用&#39;任何&#39;代替空括号,但也不起作用。

这里是跟踪所指的第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} />

1 个答案:

答案 0 :(得分:0)

选项1

class LoginView extends React.Component<{}, ILoginState> {
   constructor({}) {
   }
}

选项2

class LoginView extends React.Component<null, ILoginState> {
   constructor(null) {
   }
}

由于props的默认值是一个空对象,因此我个人更喜欢选项1。

此外,您可能希望看到this answer