简体   繁体   English

如何在react.js中声明var?

[英]How to declare a var in react.js?

I am trying to integrate my javascript code into the source code of an existing react.js project. 我正在尝试将我的javascript代码集成到现有react.js项目的源代码中。

ESLint doesn't allow for var declaration it seems, and I don't understand why. ESLint似乎不允许使用var声明,我也不明白为什么。

var distortion = new Tone.Distortion({
  distortion  : 0.6 ,
  oversample  : "3x" 
});

Variable definitions are not allowed in specific conditions in React. 在React中的特定条件下不允许使用变量定义。

You can't define them inside class component. 您不能在类组件中定义它们。 You can however define the variables inside React hooks (methods), but before the return statement. 但是,您可以在React挂钩(方法)中但在return语句之前定义变量。

Also, I recommend you to use variable definition with const or let instead of var. 另外,我建议您使用带有const或let的变量定义而不是var。

class SomeComponent extends Component {
 const someVar = '' // invalid
 render() {
   const someVar = '' // valid
 }
}

someComponent = () => {
  const someVar = '' // valid
  return <OtherComponent someValue={someVar} />
}

If you have class based component, then you can define the variable outside the class (before the class definition). 如果您具有基于类的组件,则可以在类外部定义变量(在类定义之前)。

const someVar = ''
class SomeComponent extends Component {
  render() {
   // use someVar in a hook
  }
}

But it arises question, why don't you use states instead? 但这引起了一个问题,为什么不使用状态呢?

If you use react class as component you can't use variables inside ,because classes are objects, but you can assign property to it: 如果将react类用作组件,则不能在内部使用变量,因为类是对象,但是可以为其分配属性:

class rComponent extends React.Component {
  distortion = new Tone.Distortion({
    distortion  : 0.6 ,
    oversample  : "3x" 
  });
  render() {
   //....
  }
}

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

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