You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
860 B

2 years ago
  1. import React from 'react'
  2. class Test extends React.Component {
  3. // constructor 属性返回对象的构造函数,用于创建和初始化在类中创建的对象
  4. constructor() {
  5. super()
  6. /* this
  7. 使用 bind 强行修正我们的 this 指向
  8. 相当于在类组件初始化的阶段就可以把回调函数的 this 修正到
  9. 永远指向当前组件实例对象 */
  10. this.handler = this.handler.bind(this) // 前面的 this.handler 是挂载到实例属性上,后面的 this.handler 是下面 handler() 方法
  11. }
  12. handler() {
  13. // 错误演示
  14. console.log(this) // 这里的 this 是 undefined
  15. // this.setState 去修改数据会报错
  16. }
  17. render() {
  18. return <button onClick={this.handler}>click</button>
  19. }
  20. }
  21. function App() {
  22. return <Test></Test>
  23. }
  24. export default App