【发布时间】:2020-01-17 10:24:44
【问题描述】:
我有一个餐厅列表组件,并且每个列表项都有一个 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 的填充以获得准确的结果,否则会引发错误。 这种行为对我来说是新的,非常出乎意料。
编辑- 构造函数中的绑定不是问题,我有那行,但这不是真正的问题。我的事件工作得很好,但只有当我点击 li 而不是它的任何孩子时。
【问题讨论】:
-
尝试在构造函数中初始化
this.handleReviewsconstructor(props) { super(props); this.state = { reviews: {} }; this.handleReviews = this.handleReviews.bind(this);// add this line }
标签: javascript reactjs onclick event-handling dom-events