reactjs - 在下拉项上使用 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);
}
}
};
解决方案
我相信你正在努力
onClick={() => props.appendChoiceList(props.totalWorkloadOptions.optionTitle, op)}
不是.bind()
我认为你对.bind
. 看看来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind的语法
推荐阅读
- ios - 编程 UICollectionViewController 中的空白自定义集合单元格
- javascript - nabvar 的 Javascript 按钮不起作用
- docker - zull, eureka server, eureka service 和 docker
- r - 在R中查找几个没有标题的CSV
- python - 如何让 httpretty 在测试期间停止打印异常?
- python - 如何简化这一小段代码?
- javascript - 为什么我的代码只在 javascript 中将此值增加 1 次
- c++ - 没有函数模板的实例与参数列表匹配,参数类型为:(std::string, CommandLineArgumentTypes)
- linux - 如果变量不为空,则 Bash 执行代码
- python - 计算列中的时间值