xgqfrms™, xgqfrms® : xgqfrms's offical website of cnblogs! xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

转换 React 为TypeScript

转换 React 为TypeScript

JavaScript

import React from 'react';
import PropTypes from 'prop-types';

class Input extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      value: '',
    };
    this.handleChange= this.handleChange.bind(this);
  }

  handleChange(event) {
    this.setState({ value: event.currentTarget.value });
  }

  render() {
    return (
      <div className="input__container">
        <span>{this.props.label}</span>
        <input value={this.state.value} onChange={this.handleChange} />
      </div>
    );
  }
}

Input.propTypes = {
  label: PropTypes.string.isRequired,
};

export default Input;

TypeScript

import * as React from 'react';

export interface IProps {
  label: string;
}

export interface IState {
  value: string;
}

class Input extends React.Component<IProps, IState> {

  constructor(props: IProps) {
    super(props);
    this.state = {
      value: '',
    };
    this.handleChange = this.handleChange.bind(this);
  }

  private handleChange(event: React.FormEvent<HTMLInputElement>): void {
    this.setState({ value: event.currentTarget.value });
  }

  public render(): JSX.Element {
    return (
      <div className="input__container">
        <span>{this.props.label}</span>
        <input value={this.state.value} onChange={this.handleChange} />
      </div>
    );
  }
}

export default Input;

立即捕获错误 & JavaScript可维护性。

  1. Imports

https://github.com/Microsoft/TypeScript/wiki/What's-new-in-TypeScript#support-for-default-import-interop-with-systemjs

  1. IProps & IState 接口

https://www.typescriptlang.org/docs/handbook/interfaces.html

  1. private & public

  2. code completion

这不是免费的 - 代码更冗长和更长,加上实际进行转换的成本。
如果你有一个大的现有项目,那么你和你的团队必须做出一个非常琐碎的决定,看看它是否值得转换。

https://devsandbox.io/articles/converting-react-to-typescript/


©xgqfrms 2012-2020

www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


posted @ 2017-06-08 19:54  xgqfrms  阅读(166)  评论(2编辑  收藏  举报