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.

27 lines
868 B

2 years ago
  1. import React from 'react'
  2. class Test extends React.Component {
  3. handler() {
  4. // 错误演示
  5. console.log(this) // 这里的 this 是 undefined
  6. // this.setState 去修改数据还可以修改数据吗? 会报错
  7. }
  8. render() {
  9. /* render this react
  10. 这里的 this 就是指向当前的组件实例对象
  11. 函数箭头中的 this 直接沿用所以也是指向组件的实例对象 */
  12. console.log('父函数中的 this 指向为:', this)
  13. return (
  14. /*
  15. 如果不用 constructor 做修正直接可以在事件绑定的位置通过箭头函数的写法直接沿用父函数中的this指向也是可以的 */
  16. <button onClick={() => this.handler}>click</button>
  17. )
  18. }
  19. }
  20. function App() {
  21. return <Test></Test>
  22. }
  23. export default App