将jsx转换为tsx?

11

我有一个具有定义的属性类型的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
}

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


1
你的IDE中是否可以使用简单的正则表达式替换呢? - Fez Vrasta
我的回答有帮助吗? - Ben Smith
2个回答

10
您可以使用react-javascript-to-typescript-transform软件包自动将React JSX转换/移植到Typescript TSX。
代码可以通过CLI进行转换,例如:
react-js-to-ts reactFile.js

以下示例摘自项目网站。标准的React组件,例如:
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 });
}
}

将被转换为以下typescript文件:

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 });
}
}

0
有没有任何工具可以帮助移植代码?
没有。要么自己创建一个(并链接回来),要么手动操作,或者使用任何可用的东西进行快速启动。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接