react 中事件中 绑定this 的 4 种写法,以及箭头函数绑定会出现的问题
参考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>
);
}
}
以上是 react 中事件中 绑定this 的 4 种写法,以及箭头函数绑定会出现的问题 的全部内容, 来源链接: utcz.com/z/381986.html