我这里有一些组件。父组件 (Dropdown) 有两个子组件,每个子组件都有一个在 Dropdown 中触发的单击事件。我对第一个单击事件 (handleClick) 没有任何问题,但第二个单击事件 (handleItemClick) 的绑定(bind)似乎失败
错误:
Dropdown.js:57 Uncaught TypeError: Cannot read property 'handleItemClick' of undefined
父组件(下拉菜单):
export class Dropdown extends Component {
constructor(props) {
super(props);
this.state = { open: false };
this.handleClick = this.handleClick.bind(this);
this.handleItemClick = this.handleItemClick.bind(this);
}
handleClick() {
this.setState({ open: !this.state.open });
}
handleItemClick() {
console.log("anything");
}
render() {
let list = this.props.items.map(function(item) {
return <ListItem item={item} key={item} whenItemClicked={this.handleItemClick}/>
});
return (
<div className="dropdown">
<Button
className="btn-default"
title={this.props.title}
subTitleClassName="caret"
whenClicked={this.handleClick} />
<ul className={"dropdown-menu " + (this.state.open ? "show" : "")}>
{list}
</ul>
</div>
);
}
}
子组件(ListItem),该item对应的点击事件是绑定(bind)失败的。
export class ListItem extends Component {
render() {
return (
<li><a onClick={this.props.whenItemClicked}>{this.props.item}</a></li>
);
}
}
第二个子组件,该项目对应的点击事件起作用
export class Button extends Component {
render() {
return (
<button onClick={this.props.whenClicked} className={"btn " + this.props.className} type="button">
{this.props.title} <span className={this.props.subTitleClassName}>{this.props.subTitle}</span>
</button>
);
}
}
这可能是我忽略的显而易见的事情。任何帮助将不胜感激!
最佳答案
map
会将 this
绑定(bind)到函数调用者,即数组。用 function () {}
编写的 map
中的 this
是数组而不是组件。
改用箭头函数,它将保留“词汇”this
、周围的this
,这是您的组件。
let list = this.props.items.map(item => {
return <ListItem whenItemClicked={this.handleItemClick}/>
});
关于javascript - ES6/React 第二项绑定(bind)失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36657859/