react中不使用bind

Losing bind(this) in react.md

普通的写法

import React, { Component } from "react";

class ButtonWithBind extends Component {
constructor() {
super();

this.state = { toggle: false };
}

toggleButton() {
this.setState(prevState => ({ toggle: !prevState.toggle }));
}

render() {
const toggle = this.state.toggle;

return (
<div>
        <button onclick="{this.toggleButton}">
{toggle ? "ON" : "OFF"}
</button></div>
);
}
}

export default ButtonWithBind;

如果这个时候你点击这个按钮,会出现一个错误,表示这个 toggleButton函数没有定于。

我们可以通过在toggleButton 上绑定 this 来修复这个问题

this.toggleButton = this.toggleButton.bind(this);
import React, { Component } from "react";
class ButtonWithBind extends Component {
constructor() {
super();
this.state = { toggle: false };
this.toggleButton = this.toggleButton.bind(this);
}
render() {
const toggle = this.state.toggle;
return (
<div>
        <button onclick="{this.toggleButton}">
{toggle ? "ON" : "OFF"}
</button></div>
);
}
toggleButton() {
this.setState(prevState => ({ toggle: !prevState.toggle }));
}
}
export default ButtonWithBind;

拯救写法

toggleButton = () => {
this.setState(prevState => ({ toggle: !prevState.toggle }));
}

是不是非常的熟悉?

使用箭头函数能够直接指向他的上下文。这样就不用使用.bind(this)了

import React, { Component } from "react";
class ButtonWithoutBind extends Component {
constructor() {
super();
this.state = { toggle: false };
}
render() {
const toggle = this.state.toggle;
return (
<div>
        <button onclick="{this.toggleButton}">
{toggle ? "ON" : "OFF"}
</button></div>
);
}
toggleButton = () => {
this.setState(prevState => ({ toggle: !prevState.toggle }));
}
}

除了上述写法,其实也可以在render中使用一个箭头函数来拯救你的.bind(this)

import React, { Component } from "react";
class ButtonWithBind extends Component {
constructor() {
super();
this.state = { toggle: false };
// this.toggleButton = this.toggleButton.bind(this);
}
render() {
const toggle = this.state.toggle;
return (
<div>
        <button onclick="{()=">{this.toggleButton()}}>
{toggle ? "ON" : "OFF"}
</button></div>
);
}
toggleButton() {
this.setState(prevState => ({ toggle: !prevState.toggle }));
}
}
export default ButtonWithBind;

通过<button onclick="{()=">{this.toggleButton()}}&gt;这里新生成一个匿名函数直接调用,作用域的this还是正确的

References

Losing .bind(this) in React

分享到:

发表评论

昵称

沙发空缺中,还不快抢~