gpt4 book ai didi

javascript - 如何访问方法内部的属性?

转载 作者:行者123 更新时间:2023-11-30 11:06:44 24 4
gpt4 key购买 nike

我试图让用户点击“显示问题”按钮,以便通过调用 handleQuestion() 来改变状态,但我收到以下错误声明“问题未定义”。

我想知道哪里做错了,或者有更现实的方法吗

class App extends React.Component {

constructor(props){
super(props);
this.state = {
question : [],
};
}

questions = [
{
question: "Who is the strongest?",
answers: {
a: "Superman",
b: "The Terminator",
c: "Waluigi, obviously"
},
];

handleQuestion(){
this.setState({
question: questions
});
}

render(){
return (
<div className = "container">
<button type="button" onClick={()=>this.handleQuestion()}>
Show Question
</button>
</div>
);
}
}

最佳答案

可以使用上下文 this 访问类中的属性。所以,这会很好地工作:

this.setState({
question: this.questions
})

您用来声明 questions 的语法非常新(请参阅 stage3 -> class field ),您的环境可能支持也可能不支持。

如果不行,您也可以使用像这样的函数包装器:

questions() {
return [...]
}

然后你可以这样做:

question: this.questions()

或者在类之外或在 handleQuestion 方法本身内部设置 questions。这样您就不需要使用 this 来访问 questions

关于javascript - 如何访问方法内部的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55312854/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com