[英]React JS Uncaught Reference Error: function not defined
我试图在 ReactJs 组件中的点击事件时调用 shuffleCards。 但是,我收到以下错误:
Uncaught ReferenceError: shuffleCards is not defined
这是我的代码:
constructor(props) {
super(props);
this.state = {
count: 0
};
}
shuffleCards(array) {
var i = array.length,
j = 0,
temp;
while (i--) {
j = Math.floor(Math.random() * (i+1));
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
}
handleClickEvent(event) {
var cards = [
{txt: "A",
isDisplayed: false},
{txt: "B",
isDisplayed: false},
{txt: "C",
isDisplayed: false}
];
if (this.state.count == 0) {
cards = shuffleCards(cards);
}
}
编辑刚刚看到评论,并且zerkms已经为您提供了解决方案。 我会留下我的答案以澄清澄清。
handleClickMethod
,你正在调用shuffleCards
而不是this.shuffleCards
shuffleCards(array) { // ... } handleClickEvent(event) { // ... if (this.state.count == 0) { cards = this.shuffleCards(cards); // here you should use `this.` } }
原因是因为shuffleCards
方法是在您的组件上定义的,可以通过this
属性从其方法访问它。
如果定义shuffleCards
的内handleClickMethod
,那么你可以把它无需访问this
:
handleClickEvent(event) { function shuffleCards(array) { // ... } // ... if (this.state.count == 0) { cards = shuffleCards(cards); // here you don't need `this.` } }
这对你有用吗? 在这里演示: http : //codepen.io/PiotrBerebecki/pen/qaRdgX
你在handleClickEvent
方法中引用shuffleCards
时错过了this
。
shuffleCards(array) {
// logic here
}
handleClickEvent(event) {
cards = this.shuffleCards(cards);
}
render() {
return (
<button onClick={this.handleClickEvent.bind(this)}>Click me</button>
);
}
我有同样的问题。
我升级了“ react-scripts ”并解决了这个问题。
大概解决这个问题。
npm i react-scripts
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.