参考react官方文档事件
第一种: 箭头函数绑定(需要传参数)onClick={() => this.handleClick(index)}
import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { id: 1, title: "学习react", isLike: false } ] }; } handleClick(index) { console.log(index); } render() { const { list } = this.state; return ( <div> <ul> {list.map((item, index) => ( <li key={item.id} onClick={() => this.handleClick(index)}> {item.title} </li> ))} </ul> </div> ); }} export default App;
第二种 : 箭头函数不需要传参数 ()=> this.handleClick
import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { id: 1, title: "学习react", isLike: false } ] }; } handleClick() { console.log(10); } render() { const { list } = this.state; return ( <div> <ul> {list.map((item, index) => ( <li key={item.id} onClick={() => this.handleClick()}> {item.title} </li> ))} </ul> </div> ); }} export default App;
第三种 : 再 constructor 构造中绑定this (推荐), 箭头函数有性能问题
但如果你不写 this.handleClick = this.handleClick.bind(this),以前是不支持的, 但它在新版的 Create React App 模板中已经支持了
import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { id: 1, title: "学习react", isLike: false } ] }; this.handleClick = this.handleClick.bind(this); } handleClick() { console.log(10); } render() { const { list } = this.state; return ( <div> <ul> {list.map((item, index) => ( <li key={item.id} onClick={this.handleClick}> {item.title} </li> ))} </ul> </div> ); }} export default App;
第4种 : 还是箭头函数(推荐) ,这种写法 babel 已支持,而且Create React App 模板也支持这种写法
import React, { Component } from "react"; class App extends Component { constructor(props) { super(props); this.state = { list: [ { id: 1, title: "学习react", isLike: false } ] }; } handleClick = () => { console.log(10); }; render() { const { list } = this.state; return ( <div> <ul> {list.map((item, index) => ( <li key={item.id} onClick={this.handleClick}> {item.title} </li> ))} </ul> </div> ); }} export default App;
ps: 阻止默认行为 preventDefault();
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> ); }}
---------------------
作者:素燃
来源:CSDN
原文:https://blog.csdn.net/qq_36407748/article/details/89713902
版权声明:本文为素燃原创文章,转载请附上博文链接!