6. react - 事件绑定
1. 事件绑定方式一: 全局方法返回react dom 方式绑定
function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } // 使用 onClick={handleClick} 绑定事件 return ( <a href="#" onClick={handleClick}> Click me </a> ); } var element = ActionLink() // 返回一个reactDom class Parent extends React.Component { constructor (props) { super(props) } render () { return ( <div> {element} // 挂载reactDom </div> ) } }
2. 绑定事件方式二: 成员方法绑定
构造方法中改变this指向: this.handleClick = this.handleClick.bind(this);
rend 方法的dom中绑定事件: onClick={this.handleClick}>
class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // 为了在回调中使用 `this`,这个绑定是必不可少的 this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(state => ({ isToggleOn: !state.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } } ReactDOM.render( <Toggle />, document.getElementById('root') );
3. 如果不使用 Function.prototype.bind 改变 this 指向,怎么绑定事件? 有两种方式:
方式1: 使用 public class fields 语法 。 官方建议使用该方式。
方式2:使用箭头函数。每次渲染都会创建不同的回调。如果该回调作为参数传递给子组件时,会触发重新渲染,有性能问题。
// 方式1 class LoggingButton extends React.Component { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 // 注意: 这是 *实验性* 语法。 handleClick = () => { console.log('this is:', this); } render() { return ( <button onClick={this.handleClick}> Click me </button> ); } }
// 方式2 class LoggingButton extends React.Component { handleClick() { console.log('this is:', this); } render() { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 return ( <button onClick={() => this.handleClick()}> Click me </button> ); } }
4. 事件处理函数中传递参数
// 1. 箭头函数传递参数
<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
// 2. 普通方式 <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>
// 3. 匿名函数
<button onClick={function (e) { this.deleteRow(id, e) }.bind(this)}>Delete Row</button>
class LoggingButton extends React.Component { handleClick1(e, id) { console.log(e, id) } handleClick2(id, e) { console.log(id, e) } render() { // 此语法确保 `handleClick` 内的 `this` 已被绑定。 return ( <div> <button onClick={(e) => this.handleClick1(e, "id1")}> // 事件对象 和 其他参数传递 Click me 1 </button> <button onClick={this.handleClick2.bind(this, "id2")}> // 实参传递, 默认传递事件对对象为第二个参数 Click me 2 </button> </div> ); } } ReactDOM.render( <LoggingButton />, document.getElementById('root') );
注意事项:
1. react 中事件默认行为不能通过 return false 阻止,必须 e.preventDefault();
2. react 中的事件对象 e 不是原生的事件对象,是包装后的;
this.deleteRow.bind(this, id)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)