关于antd 示例代码的this绑定问题

#1

最近在用antd, 因为之前接触react 比较少,看到示例代码的this绑定问题,感觉很疑惑。

import { Switch, Button } from 'antd';

class App extends React.Component {
  state = {
    disabled: true,
  }
  toggle = () => {
    this.setState({
      disabled: !this.state.disabled,
    });
  }
  render() {
    return (
      <div>
        <Switch disabled={this.state.disabled} defaultChecked />
        <br />
        <Button type="primary" onClick={this.toggle}>Toggle disabled</Button>
      </div>
    );
  }
}

ReactDOM.render(<App />, mountNode);

我记得 使用React.Compoent 创建React 实例的时候 函数必须手动绑定this,不然获取不到当前的实例对象,但是为什么antd 中是这么写的? 没有绑定this,也能使用?

emmmm 还有为啥 state 是直接定义的啊?

  state = {
    disabled: true,
  }

通常不是应该定义在constructer 函数中么

#2

把es6的基础看了,有你想要的答案。

#3

https://blog.csdn.net/beverley__/article/details/78547973
这里有你要的答案

#5

首先你要知道绑定this是为了干什么,此处toggle箭头函数本身就指向的App,那么你还需要在onClick去绑定this嘛?
至于第二个问题,class本质还是构造函数和原型链,在constructor内定义state和在App内定义就参照function App(){this.state={}}和App.prototype.state={}

#6

感谢 发帖之后才发现第一个问题是没看仔细,但是发现帖子已经更改不了了。感谢回答第二个问题。

#7

不过是不是在constructer 中定义state 比较常见? 除了在antd 的示例代码中,好像我还真很少看见在App中直接定义state

#8

http://lib.csdn.net/article/reactnative/56052

#9

你的疑问分解成两点:

  1. 为什么没有手动绑定this
    答:方法是用箭头函数定义的,而箭头函数本什么没有this,谁调用箭头函数,this就指向谁。如果不用箭头函数来定义方法,就必须在构造函数中使用bind来绑定this.
  2. 为什么state直接写在外面
    答:这是ES6的一种提案,直接写在类中的属性被称为实例属性,和写在构造函数constructor中是等价的。
#10

不是这样吧。箭头函数相当于bind了父层的环境。
例子:

a = {
	name: 'your name',
	age: "YOUR AGE",
	sayName: () => console.log(this.name),
	sayAge: function(){console.log(this.age)}
}

1 Like