React.js-无法访问tsx函数内部的类变量

时间:2019-05-07 16:47:13

标签: reactjs spfx tsx

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

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>
    }

}

2 个答案:

答案 0 :(得分:0)

将函数变量带到构造函数之外。 Btw render方法应该在构造函数之外。

答案 1 :(得分:0)

尝试不要在反应上使用privatepublichere是一些解释,您可以使用:

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>
    )
  }
}