gpt4 book ai didi

javascript - ReactJS PreventDefault 当已经传递参数时

转载 作者:行者123 更新时间:2023-12-03 01:31:23 28 4
gpt4 key购买 nike

我的 onClick 按钮正在调用函数 getUserInput(i, event),但是,由于 onClick 事件已绑定(bind) ( bind) 到 (this, id),我不明白如何传递“event”参数?

功能:

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 通过在开头添加传递给它的参数和默认参数并将函数绑定(bind)到正确的上下文来返回一个新函数,因此当您编写时

onClick={this.getUserInput.bind(this, id)}

getUserInput 接收 id 作为第一个参数,默认参数(即事件)作为第二个参数,因此您不需要显式传递它

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

关于javascript - ReactJS PreventDefault 当已经传递参数时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51280512/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com