Losing bind(this) in react.md

普通的写法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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 来修复这个问题

1
this.toggleButton = this.toggleButton.bind(this);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;

拯救写法

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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