[英]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.