[英]How to declare a var in react.js?
我正在嘗試將我的javascript代碼集成到現有react.js項目的源代碼中。
ESLint似乎不允許使用var
聲明,我也不明白為什么。
var distortion = new Tone.Distortion({
distortion : 0.6 ,
oversample : "3x"
});
在React中的特定條件下不允許使用變量定義。
您不能在類組件中定義它們。 但是,您可以在React掛鈎(方法)中但在return語句之前定義變量。
另外,我建議您使用帶有const或let的變量定義而不是var。
class SomeComponent extends Component {
const someVar = '' // invalid
render() {
const someVar = '' // valid
}
}
someComponent = () => {
const someVar = '' // valid
return <OtherComponent someValue={someVar} />
}
如果您具有基於類的組件,則可以在類外部定義變量(在類定義之前)。
const someVar = ''
class SomeComponent extends Component {
render() {
// use someVar in a hook
}
}
但這引起了一個問題,為什么不使用狀態呢?
如果將react類用作組件,則不能在內部使用變量,因為類是對象,但是可以為其分配屬性:
class rComponent extends React.Component {
distortion = new Tone.Distortion({
distortion : 0.6 ,
oversample : "3x"
});
render() {
//....
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.