简体   繁体   English

ES6/React 第二项绑定失败

[英]ES6/React Second item binding fails

I have a few components here.我这里有几个组件。 The parent component (Dropdown) has two sub components, each with a click event that's fired within Dropdown.父组件 (Dropdown) 有两个子组件,每个子组件都有一个在 Dropdown 中触发的点击事件。 I have no problems with the first click event (handleClick), but the binding seems to fail for the second click event (handleItemClick)我对第一个点击事件 (handleClick) 没有问题,但第二个点击事件 (handleItemClick) 的绑定似乎失败

Error:错误:

Dropdown.js:57 Uncaught TypeError: Cannot read property 'handleItemClick' of undefined

Parent component (Dropdown):父组件(下拉菜单):

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>
    );
  }
}

Child component (ListItem), this item's corresponding click event is the one failing to bind.子组件(ListItem),这个item对应的点击事件是绑定失败的那个。

export class ListItem extends Component {
  render() {
    return (
      <li><a onClick={this.props.whenItemClicked}>{this.props.item}</a></li>
    );
  }
}

Second Child component, this item's corresponding click event works Second Child组件,这个item对应的点击事件起作用

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>
    );
  }
}

This is probably something obvious that I'm overlooking.这可能是我忽略的显而易见的事情。 Any help would be greatly appreciated!任何帮助将不胜感激!

map will bind this to the function caller, which is the array. map会将this绑定到函数调用者,也就是数组。 this inside map written with function () {} is the array not the component. thisfunction () {}编写的内部map是数组而不是组件。

Use an arrow function instead, which will retain the 'lexical' this , the surrounding this , which is your component.改用箭头函数,它将保留“词法” this ,围绕this ,这是您的组件。

let list = this.props.items.map(item => { 
  return <ListItem whenItemClicked={this.handleItemClick}/>
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM