Jak*_*son 9 javascript porting transformation typescript reactjs
我有一个定义了 proptypes 的 React 组件库,我正在考虑切换到 Typescript。是否有任何工具可以帮助移植代码?这是一个简单组件的示例道具集:
static propTypes = {
active: PropTypes.bool,
children: PropTypes.node,
disabled: PropTypes.bool,
icon: Icon.propTypes.kind,
tabIndex: PropTypes.number
};
Run Code Online (Sandbox Code Playgroud)
我正在想象一个工具可以将其转换为以下内容:
static propTypes = {
active: PropTypes.bool,
children: PropTypes.node,
disabled: PropTypes.bool,
icon: Icon.propTypes.kind,
tabIndex: PropTypes.number
};
Run Code Online (Sandbox Code Playgroud)
写起来并不难,但如果它已经存在就好了。
您可以使用react-javascript-to-typescript-transform包自动将 React JSX 转换/移植到 Typescript TSX。
代码可以通过 CLI 进行转换,例如
react-js-to-ts reactFile.js
Run Code Online (Sandbox Code Playgroud)
以下示例取自项目网站。一个标准的反应组件,例如
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
将转换为以下打字稿文件:
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 });
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15724 次 |
| 最近记录: |