反应原生变量声明

时间:2018-03-24 22:34:26

标签: reactjs react-native

这些在react-native中声明变量的方式之间的区别是什么。

import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
export default class Hello extends Component {
render() {
**const var1 = 'hi';**
return ( );
}}

import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
**const var1 = 'hi';**
export default class Hello extends Component {
render() {
return ( );
}}

1 个答案:

答案 0 :(得分:3)

这些变量之间的差异是范围

在这两种情况下,due to the use of constvar1只有在 声明之后才能访问

const变量的范围是它正在运行execution context。在您的两个示例中,执行上下文是不同的。

在第二个例子中:

import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
const var1 = 'hi';
export default class Hello extends Component {
  render() {
    return ( );
  }
}

声明var1执行上下文文件

这意味着在const var1 = 'hi'; var1变量可用之后在文件的任何位置,其值为'hi'

在你的第一个例子中:

import React, { Component } from 'react';
import { AppRegistry, Image, View, Text, } from 'react-native';
export default class Hello extends Component {
  render() {
    const var1 = 'hi';
    return ( );
  }
}

声明的执行上下文是方法render()

同样,它意味着在render()方法中的render()方法const var1 = 'hi';方法之后的任何一点var1语句'hi'变量可用,其值为const var1 = 'hi';

TL;博士

总之,当您在方法中使用var1时,const var1 = 'hi';(常量)变量可用 该方法。 OTOH,当您在文件中声明{}时,在任何类或var1或函数之外,var1将在整个文件中可用。

但在这两种情况下,const var1 = 'hi';只会在a声明语句后定义/可用。