2016-09-30 119 views
6

有時您想要從無狀態組件快速轉到有狀態組件,並且我在考慮是否有某種方法可以使IntelliJ爲我執行此操作(無需創建插件)。快速從JSX React無狀態組件到JSX React在IntelliJ中的有狀態組件

例如,去從:

const Stateless = ({ propsDestructuring }) => { 
    console.log('Some logic'); 

    return (
    <div>Some JSX</div> 
); 
}; 

到:

class Stateful extends Component { 
    render() { 
    const { 
     propsDestructuring 
    } = this.props; 

    console.log('Some logic'); 

    return (
     <div>Some JSX</div> 
    ); 
    } 
} 

從 「箭體風格」,以明確的回報或者會也將是有益的,例如從

const Stateless = ({ propsDestructuring }) => (
    <div>Some JSX</div> 
); 

要:

const Stateless = ({ propsDestructuring }) => { 
    return (
    <div>Some JSX</div> 
); 
}; 

使用實時模板不會在這種情況下工作,因爲它們可以發生變異現有的代碼,只插入新的。有什麼建議麼?

+0

我認爲這可能是JetBrains可以建議的,我們可以爲它投票! https://intellij-support.jetbrains.com/hc/en-us/requests/new?ticket_form_id=66731。好想法!! –

+1

這聽起來像JSCodeShift codemods可能存在的那種東西。這裏是一個codemod從類到無狀態組件,例如:https://github.com/reactjs/react-codemod#pure-component –

回答

0

你可以從:

const Stateless = ({ propsDestructuring }) => (
    <div>Some JSX</div> 
); 

到:

const Stateless = ({ propsDestructuring }) => { 
    return (
    <div>Some JSX</div> 
); 
}; 

把你的文本光標位置:

const Stateless = ({ propsDestructuring }) => (
-----------------------------------------^----- 

,然後按Alt-Enter組合得到以下彈出:

intellij popup

再次按下輸入選擇最上面的結果,它將被轉換爲帶有大括號的箭頭功能。

至於在功能級轉化,據我所知沒有辦法做到這一點,但你總是可以嘗試使用查找和替換轉換:

const (.*) = \(.*\) => \{ 

到:

class $1 extends React.Component { 

如果你把它記錄到一個宏中,它應該加快這個操作的速度。