4.事件练习:计数器.html 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8" />
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  7. <title>Document</title>
  8. <script src="../../babel.min.js"></script>
  9. <script src="../../react.development.js"></script>
  10. <script src="../../react-dom.development.js"></script>
  11. </head>
  12. <body>
  13. <div id="root"></div>
  14. <script type="text/babel">
  15. function App() {
  16. // 需要 我们自己创建一个对象(ref对象 ==> {current: 组件实例}) 和 要获取的组件 建立ref绑定关系
  17. const counterRef = React.createRef();
  18. const inputRef = React.createRef();
  19. return (
  20. <div className="app">
  21. <button
  22. onClick={() => {
  23. console.log(`output->counterRef`, counterRef);
  24. console.log(`output->inputRef`, inputRef);
  25. }}
  26. >
  27. 获取Counter组件实例
  28. </button>
  29. <input type="text" ref={inputRef} />
  30. {/*通过组件元素的ref属性 和 上面创建的ref对象 建立绑定关系*/}
  31. <Counter ref={counterRef} />
  32. </div>
  33. );
  34. }
  35. class Counter extends React.Component {
  36. constructor(props) {
  37. super(props);
  38. this.state = {
  39. c: 0,
  40. };
  41. this.handleAddOne = this.handleAddOne.bind(this);
  42. }
  43. handleAddOne() {
  44. // this
  45. // ? this.state.c 是上一次状态吗。不一定。因为 setState状态的更新 可能是异步的
  46. // 如果当前新状态 的值 需要依赖 上一次状态的值 运算才能计算出 这个时候 就不能像下面方式写
  47. // this.setState({ c: this.state.c + 1 });
  48. // 为了 准确获取上一次状态 可以给 setState方法 传入一个回调函数:该函数会接收两个参数:prevState、props。传入的回调函数 在返回一个新的状态对象即可
  49. this.setState((prevState) => {
  50. return { c: prevState.c + 1 };
  51. });
  52. }
  53. render() {
  54. let { c } = this.state;
  55. return (
  56. <div className="counter">
  57. <p>当前计数:{c}</p>
  58. <p>
  59. <button
  60. onClick={() => {
  61. // this
  62. this.setState(({ c }) => ({ c: c - 1 }));
  63. }}
  64. >
  65. -
  66. </button>
  67. <button onClick={this.handleAddOne}>+</button>
  68. </p>
  69. </div>
  70. );
  71. }
  72. }
  73. const root = ReactDOM.createRoot(document.querySelector('#root'));
  74. root.render(<App />);
  75. </script>
  76. </body>
  77. </html>