简体   繁体   English

React Native扩展多个组件与createClass

[英]React Native Extending Multiple Components vs createClass

I've seen many tutorials with code that suggests doing something like the following: 我已经看过很多教程,其中的代码建议执行以下操作:

var App = React.createClass({
    someFunction() { .. },
    render() { return(); },
});
var Lication = React.createClass({
    someOtherFunction() { .. },
    render() { return(); },
});

...but I've been using the ES6 syntax: ...但我一直在使用ES6语法:

class App extends Component {
    someFunction() { .. }
    render { return(); }
}

Where do I create the Lication class? 我在哪里创建Lication类? Right below the App class? App类正下方? Or does it need its own file, and imported into the main file with something like: 或者它是否需要自己的文件,并导入到主文件中,例如:

var Lication = require('./Lication');

I have yet to see code that uses multiple classes. 我还没有看到使用多个类的代码。

Where do I create the Lication class? 我在哪里创建Lication类? Right below the App class? App类正下方? Or does it need its own file? 或者它需要自己的文件?

Using ES6 classes or React's createClass function makes no rules about where you have to define them. 使用ES6类或React的createClass函数不会规定您必须定义它们的位置。 Both can be defined one above another or in different files. 两者都可以在另一个上面或在不同的文件中定义。 The one way using ES6 classes does affect code order is with hoisting : 使用ES6类的单向方式确实会影响代码顺序,并且需要提升

An important difference between function declarations and class declarations is that function declarations are hoisted and class declarations are not. 函数声明和类声明之间的一个重要区别是函数声明被提升而类声明不被提升。 You first need to declare your class and then access it. 首先需要声明您的类然后访问它。

Which means something like this is invalid: 这意味着这样的事情是无效的:

var l = new Lication(); // ReferenceError

class Lication {}

As far as splitting the code into files or not, this is valid: 至于将代码拆分成文件,这是有效的:

class App extends React.Component {
  // ...
}

class Lication extends React.Component {
  // ...
}

And so is this: 这是这样的:

class App extends React.Component {
  // ...
}

var Lication = require('path-to-lication-class');

Where Lication would be defined in its own file and exported out: Lication将在其自己的文件中定义并导出:

class Lication extends React.Component {
  // ...
}

module.exports = Lication;

The last example is essentially equivalent to: 最后一个例子基本上相当于:

class App extends React.Component {
  // ...
}

var Lication = class Lication extends React.Component {
  // ...
}

Splitting into files is done to achieve modularity in your code, where individual components are split into files (or modules) so they can be easier to maintain and the whole app isn't crowded into one giant file while developing but combined later when deploying. 分割成文件是为了在代码中实现模块化,其中单个组件被分成文件(或模块),因此它们可以更容易维护,整个应用程序在开发时不会挤在一个巨大的文件中,但在部署后会合并。

Here's a useful read on classes 这是关于类有用读物

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

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