12.this指向.html 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. <script src="./babel.min.js"></script>
  8. <script src="./react.development.js"></script>
  9. <script src="./react-dom.development.js"></script>
  10. </head>
  11. <body>
  12. <div id="root"></div>
  13. <script type="text/babel">
  14. const root = ReactDOM.createRoot(document.getElementById("root"));
  15. let aa = <h1>111</h1>
  16. // 1.监听器的this 实际开发时 是在类组件中
  17. // 2.类数组中 绑定事件时 => this.xxx 此时 事件的this指向是undefined
  18. // 3.修改this指向:bind apply call
  19. function Goods() {
  20. function handleClick() {
  21. let aa = '12';
  22. aa = 22;
  23. console.log("点击了1",aa)
  24. }
  25. return <button onClick={handleClick}>你好哈哈哈</button>;
  26. }
  27. class Good extends React.Component {
  28. constructor() {
  29. super();
  30. this.state = {
  31. hi:"你好啊"
  32. }
  33. this.handleClick = this.handleClick.bind(window);
  34. }
  35. handleClick() {
  36. console.log("点击了",this)
  37. this.setState({
  38. hi:"你好,世界"
  39. })
  40. }
  41. render() {
  42. return <button onClick={this.handleClick}>{this.state.hi}</button>;
  43. // return <button onClick={this.handleClick.bind(this)}>{this.state.hi}</button>;
  44. }
  45. }
  46. root.render(<Goods />);
  47. // let obj = {
  48. // fn1() {
  49. // console.log('fn1',this);
  50. // return 1;
  51. // },
  52. // aa: 12
  53. // }
  54. // obj.fn1(); //指向对象
  55. // let a = obj.fn1;
  56. // a(); // undefined
  57. // a.call(window);
  58. </script>
  59. </body>
  60. </html>