我无法访问 App 类中的状态变量。有人可以推荐我一些解决方案吗?
class App extends React.Component {
constructor(props) {
super(props);
var question1 = [
"What is 8*1",
"What is 8*2",
"What is 8*3",
"What is 8*4"
];
var choice = ["1", "2", "4", "8", "9"];
this.state = {
question1: this.question1,
choice: this.choice,
correct: 0,
incorrect: 0
};
console.log(this.state.choice);
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler() {
console.log("hello world");
}
render() {
return (
<div>
<Question question={this.state.question1} choice={this.state.choice} />
</div>
);
}
}
最佳答案
删除 this.question1
和 this.choice
中的 this
并且总是更喜欢 let
/const
而不是 var
;
constructor(props) {
super(props);
const question1 = [
"What is 8*1",
"What is 8*2",
"What is 8*3",
"What is 8*4"
];
const choice = ["1", "2", "4", "8", "9"];
this.state = {
question1: question1,
choice: choice,
correct: 0,
incorrect: 0
};
this.clickHandler = this.clickHandler.bind(this);
}
关于javascript - 访问状态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62169585/