首页 > 解决方案 > 像这样在 react-native 中实现 js 类命名有什么区别

问题描述

从一些教程中,我看到了实现这个原生 js react 类的不同,我想知道,在与这个实现的差异相关的功能方面是否存在差异?

首先像这样

import React, {Component} from 'react';

export default class App extends Component {

}

第二个像这样

import React, {Component} from 'react';

class App extends Component {

}

export default App;

有什么不同吗?

标签: react-native

解决方案


使用它时没有区别。任何一个都将此类成员导出为默认值。我认为这归结为偏好以及您认为更清晰的代码。

有人可能会说类声明应该就是:声明类。然后,如果您想使用导出,请将它们放在底部,特别是如果您想要导出的文件中有多个类。这样,所有导出都在代码的一部分中可见。

import React, {Component} from 'react';

class App extends Component {
    // ...
}

class Page extends Component {
    // ...
}

class Service extends Component {
    // ...
}

// you have all of your exports together
export App;
export Page;
export Service;

To further expand on that, if you use Typescript, the class declaration can take a lot of characters to fit in one line. And thus if you are trying to write clean, "linted" code, you would want to keep the length of your lines at bay. And to avoid unnecessary long line, you would just do that separately, after the code.

import React, {Component} from 'react';

interface State {
    // ...
}

interface Props {
    // ...
}

class App extends Component<Props, State> {
    // ...
}

export default App;

In the end of the day, it's up to you or your team, and comes down to purely aesthetic/clean code purposes.


推荐阅读