我有一个餐厅列表组件,并且每个列表项都有一个 onClick 事件。一切工作正常,除非我单击列表项的任何子元素。它没有任何响应或未定义(我不知道,因为控制台中没有显示任何内容。) 这是我的组件:
import React from "react";
class ResturantsList extends React.Component {
constructor(props) {
super(props);
this.state = {
reviews: {}
};
}
handleReviews = e => {
const reviewsList = this.props.resturants.find(
resturant => resturant.id === e.target.id
);
console.log(reviewsList.reviews);
};
render() {
let list = this.props.resturants.map(resturant => {
return (
<li
key={resturant.id}
id={resturant.id}
className="resturant"
onClick={this.handleReviews}
>
<div className="resturant__hero">
<h1 className="resturant__name">{resturant.name}</h1>
<img src={resturant.icon} alt="" className="resturant__icon" />
</div>
<div className="resturant__row">
<p className="item">Rating</p>
<p className="description">{resturant.rating || "N/A"}</p>
</div>
</li>
);
});
return <div>{list}</div>;
}
}
export default ResturantsList;
所以问题是我只能单击 li 的填充才能获得准确的结果,否则会引发错误。 这种行为对我来说是新的并且非常出乎意料。
编辑- 构造函数中的绑定(bind)不是问题,我有那行,但这不是真正的问题。我的事件工作得很好,但只有当我点击 li 而不是它的任何子事件时。
最佳答案
Use e.currentTarget
尝试在 handleReviews()
中使用 e.currentTarget
而不是 e.target
,如下所示:
handleReviews = e => {
const reviewsList = this.props.resturants.find(
resturant => resturant.id === e.currentTarget.id // <--- Here
);
console.log(reviewsList.reviews);
};
关于javascript - 单击子元素会给 onclick 事件reactjs 带来未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59785469/