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

标签 javascript html reactjs

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

相关文章:

javascript - 我可以使用 d3.js 显示 GraphViz 生成的点或 xdot 布局文件吗?

html - 我的样式表无法正常工作/链接不正确

javascript - React.JS - 多个元素共享一个状态(如何仅修改其中一个元素而不影响其他元素?)

javascript - setState 意外更新非状态属性

javascript - MapView 组件中状态和初始区域的 React Native 问题

javascript - Framer.js : how do you get the "previous" layer?

javascript - 如何通过一个 onclick 事件更改两个单独的图像?

javascript - jQuery ui 自动完成 - renderItem

javascript - Onload 删除单选按钮值

php - highcharts不显示图表