2016-05-29 658 views
2

我有一個定義了proptypes的React組件庫,正在考慮切換到Typescript。有沒有任何工具可以幫助移植代碼?下面是一個簡單的組件設置道具的例子:將jsx轉換爲tsx?

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更換? –

回答

0

是否有任何工具,這將有助於將代碼移植

都能跟得上。或者創建一個(並鏈接回)或者只是使用手動工作或僅使用any來快速啓動

0

您可以使用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 }); 
} 
}