且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

无法在REACT中的类中使用常量

更新时间:2023-11-07 10:18:10

您不能真的在"就像那样"的类中使用const

class App extends React.Component {
  const a = 2 // will throw a syntax error
  render(){
   return <div>Hello World</div>
  }

您可以做的是不使用常量将变量声明为类字段:

class App extends React.Component {
   a = "john";

  render(){
   //now you can access a via `this`
   return <div>{`Hello ${this.a}`}</div>
  }

或者,如果您不需要以某种方式将其"绑定"到组件,则可以在类外部声明它。

const a = "john"

class App extends React.Component {
  render(){
   //you can simply access `a` 
   return <div>{`Hello ${a}`}</div>
  }