【问题标题】:Convert jsx to tsx?将 jsx 转换为 tsx?
【发布时间】:2016-09-27 02:48:38
【问题描述】:

我有一个定义了 proptypes 的 React 组件库,我正在考虑改用 Typescript。是否有任何工具可以帮助移植代码?这是一个简单组件的一组示例道具:

  static propTypes = {
    active: PropTypes.bool,
    children: PropTypes.node,
    disabled: PropTypes.bool,
    icon: Icon.propTypes.kind,
    tabIndex: PropTypes.number
  };

我正在想象一个工具可以将它转换成类似的东西:

interface IButtonProps {
    active: boolean,
    children: node,
    disabled: boolean,
    icon: Icon,
    tabIndex: number
}

写起来不难,但如果已经存在就更好了。

【问题讨论】:

  • 在您选择的 IDE 中进行简单的正则表达式替换怎么样?
  • 我的回答有帮助吗?

标签: javascript reactjs typescript transformation porting


【解决方案1】:

有什么工具可以帮助移植代码

不。要么创建一个(并返回链接),要么只做手动工作,或者只使用any 快速开始?

【讨论】:

    【解决方案2】:

    您可以使用 react-javascript-to-typescript-transform 包自动将 React JSX 转换/移植到 Typescript TSX。

    可以通过 CLI 转换代码,例如

    react-js-to-ts reactFile.js
    

    以下示例取自项目网站。一个标准的反应组件,例如

    class MyComponent extends React.Component {
    static propTypes = {
        prop1: React.PropTypes.string.isRequired,
        prop2: React.PropTypes.number,
    };
    constructor() {
        super();
        this.state = { foo: 1, bar: 'str' };
    }
    render() {
        return (
            <div>
                {this.state.foo}, {this.state.bar}, {this.state.baz}
            </div>
        );
    }
    onClick() {
        this.setState({ baz: 3 });
    }
    }
    

    将转换为以下打字稿文件:

    type MyComponentProps = {
    prop1: string;
    prop2?: number;
    };
    
    type MyComponentState = {
    foo: number;
    bar: string;
    baz: number;
    };
    
    class MyComponent extends React.Component<MyComponentProps, MyComponentState> {
    constructor() {
        super();
        this.state = { foo: 1, bar: 'str' };
    }
    render() {
        return (
            <div>
                {this.state.foo}, {this.state.bar}, {this.state.baz}
            </div>
        );
    }
    onClick() {
        this.setState({ baz: 3 });
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-04
      • 2016-12-01
      • 2018-11-07
      • 1970-01-01
      • 2021-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多