首页 > 解决方案 > 已经传递参数时的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>

标签: javascripthtmlreactjs

解决方案


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

推荐阅读