0

我无法访问函数内的类变量,以下是我的代码:

export class MyClass extends React.Component<{}, {}>{
  public myArray: string[]; //I want to access this variable

  constructor() {
    this.state = { name: "" }
 } 
  private _hello = () => {
    console.log(this.state.name);
    console.log(this.myArray) //this lines throws undefined
  } 
    render(){
      <button onClick={this._hello}>Click</button>
    }

}
4

2 回答 2

0

尽量不要使用privatepublic反应,这里有一些解释,你可以使用:

const myArray: string[]; //I want to access this variable

export class MyClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
    }
  }

  hello = () => {
    console.log(this.state.name);
    console.log(myArray) //this lines throws undefined
  }

  render(){
    return (
      <button onClick={this.hello}>Click</button>
    )
  }
}

于 2019-05-07T16:55:09.750 回答
0

将函数变量带到构造函数之外。顺便说一句,渲染方法应该在构造函数之外。

于 2019-05-07T16:51:35.077 回答