[英]React onClick function in map function
我嘗試在地圖函數中觸發 onClick 事件,但出現此錯誤:
TypeError:無法讀取未定義的屬性“handleClick”
我們如何在地圖函數中觸發 onClick 事件?
這是我的代碼:
class Component extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true,
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState((prevState) => ({
isToggleOn: !prevState.isToggleOn,
}));
}
render() {
if (this.props.data) {
var recipes = this.props.data.map(function (recipe, i) {
return (
<div
key={i}
className="col-8 offset-col-1 f-l relative m-t-10"
>
<div className="col-6 f-l">
<p className="col-8 f-l">{recipe.title}</p>
<button className="f-l" onClick={this.handleClick}>
Voir la recette
</button>
</div>
</div>
);
});
}
return (
<div className="RecipeList">
<div className="col-12">
{recipes}
<div className="both"></div>
</div>
</div>
);
}
}
使用箭頭函數作為給map
的函數, this
將是您所期望的:
if (this.props.data) {
var recipes = this.props.data.map((recipe, i) => {
return <div key={i} className="col-8 offset-col-1 f-l relative m-t-10">
<div className="col-6 f-l">
<p className="col-8 f-l">{recipe.title}</p>
<button className="f-l" onClick={this.handleClick}>Voir la recette</button>
</div>
</div>;
});
}
為什么會這樣, 這里會詳細解釋。 箭頭函數不提供自己的this
綁定,而是保留封閉詞法上下文的this
值。
這就是我處理類似情況的方法。
import React from "react";
import ReactDOM from "react-dom";
const stuff = ["one", "two", "three"];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
isToggleOn: true
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(val) {
console.log(val);
}
getStuff() {
var elements = stuff.map((value, key) => {
return (
<li key={key} onClick={() => this.handleClick(value)}>
{value}
</li>
);
});
return elements;
}
render() {
return <ul>{this.getStuff()}</ul>;
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
您必須在地圖參數或箭頭函數中使用this
。
this.props.data.map(function(recipe, i) {
return <div key={i} className="col-8 offset-col-1 f-l relative m-t-10">
<div className="col-6 f-l">
<p className="col-8 f-l">{recipe.title}</p>
<button className="f-l" onClick={this.handleClick}>Voir la recette</button>
</div>
</div>;
}, this)
為什么?
在這里閱讀。
如果為 map 提供了
thisArg
參數,它將被用作回調的this
值。 否則,值 undefined 將用作其 this 值。
為了更好地理解this
范圍檢查here 。 解釋this
在不同上下文中的內容,如簡單函數調用、對象方法、箭頭函數等。還解釋了如何通過bind
、 call
和apply
來控制范圍。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.