ThinkSSL🔒 一键申购 5分钟快速签发 30天无理由退款 购买更放心 广告
# 事件处理 >[success] React 元素的事件处理和 DOM元素的很相似。但是有一点语法上的不同: - React事件绑定属性的命名采用驼峰式写法,而不是小写。 - 如果采用 JSX 的语法需要传入一个函数作为事件处理函数,而不是一个字符串(DOM元素的写法) - 在 React 中不能使用返回 false 的方式阻止默认行为。你必须明确的使用 preventDefault。 比如: 传统HTML的写法 ```html <button onclick="activateLasers()"> Activate Lasers </button> ``` React中的写法 ```html <button onClick={activateLasers}> Activate Lasers </button> ``` ## 阻止默认行为 传统HTML的写法 ```html <a href="#" onclick="console.log('The link was clicked.'); return false"> Click me </a> ``` React中的写法 ```jsx function ActionLink() { function handleClick(e) { e.preventDefault(); console.log('The link was clicked.'); } return ( <a href="#" onClick={handleClick}> Click me </a> ); } ``` ## 事件处理程序 在React中使用事件处理,只需要在组件类中定义对应的方法即可,在需要处理事件的地方使用 `this.方法名` 即可 ```jsx class Toggle extends React.Component { constructor(props) { super(props); this.state = {isToggleOn: true}; // This binding is necessary to make `this` work in the callback this.handleClick = this.handleClick.bind(this); } handleClick() { this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn })); } render() { return ( <button onClick={this.handleClick}> {this.state.isToggleOn ? 'ON' : 'OFF'} </button> ); } } ``` ## 向事件处理程序传递参数 如果需要向时间处理程序传递参数,可以使用以下两种方法: ```html <button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button> <button onClick={this.deleteRow.bind(this, id)}>Delete Row</button> ``` 上述两种方式是等价的,分别通过 arrow functions 和 Function.prototype.bind 来为特定事件类型添加事件处理程序。 上面两种方式,参数 e 作为 React 事件对象将会被作为第二个参数进行传递。通过箭头函数的方式,事件对象必须显式的进行传递,但是通过 bind 的方式,事件对象以及更多的参数将会被隐式的进行传递。 需要注意的是,通过 bind 方式向监听函数传参,在类组件中定义的监听函数,由于是隐私传递,事件对象 e 要排在所有传递参数的后面。 ```jsx class Popper extends React.Component{ constructor(){ super(); this.state = {name:'Hello world!'}; } preventPop(name, e){ // 事件对象e要放在最后 e.preventDefault(); alert(name); } render(){ return ( <div> <p>hello</p> {/* Pass params via bind() method. */} <a href="https://reactjs.org" onClick={this.preventPop.bind(this,this.state.name)}>Click</a> </div> ); } } ```