我正在学习React并遇到一个疑问,有两个代码,其中组件中的render方法使用的变量在不同的地方声明,我怀疑是为什么一个工作而另一个不工作。
import React from 'react';
import ReactDOM from 'reactDOM';
const myVar = 'hello';
class myComponent extends React.Component {
render () {
return <h1>{myVar}</h1>;
}
}
ReactDOM(
<myComponent />,
document.getElementById('app')
);
这有效,意味着我能够在render方法中访问全局变量。
但是拿这个不起作用的情况
import React from 'react';
import ReactDOM from 'reactDOM';
class myComponent extends React.Component {
const myVar = 'hello';
render () {
return <h1>{this.myVar}</h1>;
}
}
ReactDOM(
<myComponent />,
document.getElementById('app')
);
我在这里很困惑,有人可以解释这种行为
在类中,您没有定义变量。你只需要写myVar='hello'
而不是const myVar='hello'
在类定义中指定的属性被赋予与它们出现在对象文字中相同的属性。