首页 > 解决方案 > 在下拉项上使用 onClick 时,bind() 不运行

问题描述

为什么我的组件方法 onClick 没有触发?当用户单击下拉项时,它应该使用 .bind() 函数激活以下方法,但没有任何反应,当在更高组件级别应用于我的应用程序的其他部分时,这可以正常工作。

渲染组件的打字稿文件:

export const Options = props => (
  <div>
    <Dropdown isOpen={props.modalDropDown} toggle={props.toggleDropDown.bind()}>
      <DropdownToggle caret>{props.totalWorkloadOptions.optionTitle}</DropdownToggle>
      <DropdownMenu>
        {props.totalWorkloadOptions.options.map(op => (
          // tslint:disable-next-line:no-invalid-this
          <DropdownItem key={op} onClick={props.appendChoiceList.bind(props.totalWorkloadOptions.optionTitle, op)}>
            {op}
          </DropdownItem>
        ))}
      </DropdownMenu>
      <strong> {props.totalWorkloadOptions.optionDescription} </strong>
    </Dropdown>
    <br />
  </div>
);

方法我试图绑定到:

appendChoiceList = (title: string, selected: string) => {
    console.log('selected:' + selected);
    console.log('new choice:' + title);
    const newOptionRequest: IWorkloadRequest = {
      optionTitle: title,
      selectedOption: selected
    };

    // tslint:disable-next-line:prefer-const
    for (let item of this.state.userChoices) {
      console.log(item);
      if (item.optionTitle === newOptionRequest.optionTitle) {
        // If user has already selected this before repalce it
        console.log(item);
        // tslint:disable-next-line:prefer-const
        let i = this.state.userChoices.indexOf(item);
        console.log(i);
        this.state.userChoices[i] = newOptionRequest;
      } else {
        // if this choice has not been set before
        this.state.userChoices.push(newOptionRequest);
      }
    }
  };

标签: reactjstypescriptonclickreactstrap

解决方案


我相信你正在努力

onClick={() => props.appendChoiceList(props.totalWorkloadOptions.optionTitle, op)}

不是.bind()

我认为你对.bind. 看看来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind的语法


推荐阅读