javascript - 已经传递参数时的ReactJS PreventDefault
问题描述
我的onClick
按钮正在调用函数getUserInput(i, event)
,但是,由于onClick
事件已绑定(bind
)到(this, id)
,我无法理解如何传递 over“事件”参数?
功能:
getUserInput = (i, event) => {
event.preventDefault();
const searchLocation = document.getElementById(i).value;
this.state.locationArray[i].location = searchLocation;
this.setState({
locationArray: this.state.locationArray
})
this.createGrid();
}
按钮:
<form className="form" role="search" autoComplete="off">
<input id={id} className="searchBar" type="search" name="searchField" placeholder={filledArray[i].name}></input>
<button onClick={this.getUserInput.bind(this, id)} value="submit" className="searchButton"><i className="fa fa-search"></i></button>
</form>
解决方案
.bind
返回一个新函数,方法是在开头添加传递给它的参数,然后是默认参数,并将函数绑定到正确的上下文,因此当你编写
onClick={this.getUserInput.bind(this, id)}
getUserInput
接收 id 作为第一个参数和默认参数,即 event 作为第二个参数,因此您不需要显式传递它
bind
函数的典型实现是
Function.prototype.bind = function(context){
var that = this,
slicedArgs = Array.prototype.splice.call(arguments, 1),
bounded = function (){
var newArgs = slicedArgs.concat(Array.prototype.splice.call(arguments, 0));
return that.apply(context,newArgs);
}
bounded.prototype = that.prototype;
return bounded;
}
推荐阅读
- python - 使用 Drive API 从 Google Drive 下载文件后无法重命名或移动文件
- json - 如何从同一个 DocumentContext 对象中提取和更新?
- linux - FBGrab 提供黑色 .png 图像
- python - 在for循环Python中修改和运行函数
- sql - 连接 3 个表时 SQL 对象名称无效
- swift - Swift:如何将 NSView 转 45 度?
- c++ - 找不到“Leptonica”提供的包配置文件
- kibana - Elasticsearch 有条件地查询多个索引
- python - Python,检查是否在'with'语句中调用
- javascript - 如何从 Bing Maps API 获取 JSON?