我无法访问函数中的类变量,以下是我的代码:
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>
}
}
答案 0 :(得分:0)
将函数变量带到构造函数之外。 Btw render方法应该在构造函数之外。
答案 1 :(得分:0)
尝试不要在反应上使用private
和public
,here是一些解释,您可以使用:
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>
)
}
}