05-React中绑定this并给函数传参的几种方式
前言
import React from "react";
export default class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
msg: "这是 MyComponent 组件 默认的msg"
};
}
render() {
return (
<div>
<h1>绑定This并传参</h1>
<input type="button" value="绑定this并传参" onClick={this.changeMsg} />
<h3>{this.state.msg}</h3>
</div>
);
}
changeMsg() {
// 注意:这里的changeMsg()只是一个普通方法。因此,在触发的时候,这里的 this 是 undefined
console.log(this); // 打印结果:undefined
this.setState({
msg: "设置 msg 为新的值"
});
}
}绑定 this 的方式一:bind()
绑定 this 并给函数传参 的方式二:构造函数里设置 bind()
绑定 this 并给函数传参 的方式三:箭头函数【荐】
Last updated