You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中如何在锚点元素上传递事件与参数?

解决React中Anchor元素传递事件与参数时e.preventDefault()报错的问题

嘿,我一眼就看出问题出在哪啦!你这段代码里调用loadComponent时传的第一个参数是this.event,这根本不是React点击事件触发时的真实事件对象,而是一个不存在的属性,所以调用e.preventDefault()才会报错说它不是函数。

给你两种靠谱的解决办法:

方法一:箭头函数接收事件对象后传递

直接在onClick的箭头函数里接收React传来的事件对象e,再把它和你的组件参数一起传给loadComponent:

// 类组件中的方法
loadComponent(e, component) {
  e.preventDefault();
  this.setState({ componentToLoad: component });
}

// JSX中的a标签
<a onClick={(e) => this.loadComponent(e, <FormatName />)}> Format Name </a>

方法二:使用bind绑定参数

利用Function.prototype.bind提前绑定你要传的组件参数,React会自动把事件对象作为第一个参数传入方法(注意这里要调整方法的参数顺序):

// 调整参数顺序,component在前,事件对象e在后
loadComponent(component, e) {
  e.preventDefault();
  this.setState({ componentToLoad: component });
}

// 用bind绑定this和组件参数
<a onClick={this.loadComponent.bind(this, <FormatName />)}> Format Name </a>

额外注意:确保this指向正确

如果你的组件是类组件,别忘了保证loadComponent方法里的this指向组件实例,有两种方式:

  1. 在构造函数中绑定this:
constructor(props) {
  super(props);
  this.loadComponent = this.loadComponent.bind(this);
}
  1. 用箭头函数定义方法(自动绑定this):
loadComponent = (e, component) => {
  e.preventDefault();
  this.setState({ componentToLoad: component });
}

内容的提问来源于stack exchange,提问作者Teoman shipahi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 06:51:26