简体   繁体   English

如何将React类组件转换为功能组件,反之亦然 - IntelliJ

[英]How to convert React class components into functional components and vice versa - IntelliJ

Sometimes you want to quickly go from a statless component to a stateful component, and I'm thinking if there is some way to make IntelliJ do this for me (without creating a plugin). 有时候你想快速从无状态组件转到有状态组件,我想是否有办法让IntelliJ为我做这个(没有创建插件)。

For example, going from: 例如,从:

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

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

to: 至:

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

    console.log('Some logic');

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

Alternatively going from "Arrow body style" to explicit return would also be useful, eg going from 或者从“箭头体型”到显式返回也是有用的,例如从

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

to: 至:

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

Using live templates would not work in this scenario, as they can't mutate existing code, only insert new. 使用实时模板在这种情况下不起作用,因为它们不能改变现有代码,只能插入新代码。 Any suggestions? 有什么建议?

IntelliJ 2018.2 now supports this. IntelliJ 2018.2现在支持这一点。

New intention to Convert React class components into functional components. 将React类组件转换为功能组件的新意图。

Instructions: 说明:

Press on the component definition: 按组件定义:

  • Mac: options + Enter Mac: 选项 + 输入

  • Windows: Alt + Enter Windows: Alt + Enter

It works both ways: 它有两种方式:

无状态到类组件

类到无状态组件

Referrence: Development with React 参考: 用React开发

You can go from: 你可以从:

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

to: 至:

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

By putting your text cursor here: 将文本光标放在这里:

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

And pressing alt-enter to get the following popup: 然后按alt-enter以获得以下弹出窗口:

intellij popup

Press enter again to select the top result and it'll be converted to an arrow function with braces. 再次按Enter键选择最高结果,它将转换为带括号的箭头功能。

With regards to the function to class conversion, as far as I'm aware there's no way to do that, but you could always try using find and replace to convert: 关于类转换的功能,据我所知,没有办法做到这一点,但你总是可以尝试使用find和replace来转换:

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

to: 至:

class $1 extends React.Component {

If you record this to a macro it should speed that operation up a little. 如果将其记录到宏中,它应该加快操作速度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM