当已经传递参数时,ReactJS PreventDefault

时间:2018-07-11 08:19:10

标签: javascript html reactjs

我的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>

1 个答案:

答案 0 :(得分:1)

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