[英]use of variable inside render function of react component
我正在學習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'
在類定義中指定的屬性被賦予與它們出現在對象文字中相同的屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.