简体   繁体   中英

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.

ESLint doesn't allow for var declaration it seems, and I don't understand why.

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

Variable definitions are not allowed in specific conditions in React.

You can't define them inside class component. You can however define the variables inside React hooks (methods), but before the return statement.

Also, I recommend you to use variable definition with const or let instead of 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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