Bläddra i källkod

React:计数器练习&组件引用

大侠 2 år sedan
förälder
incheckning
af984f98a3
1 ändrade filer med 84 tillägg och 0 borttagningar
  1. 84 0
      15_React/day-2/code/4.事件练习:计数器.html

+ 84 - 0
15_React/day-2/code/4.事件练习:计数器.html

@@ -0,0 +1,84 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Document</title>
+    <script src="../../babel.min.js"></script>
+    <script src="../../react.development.js"></script>
+    <script src="../../react-dom.development.js"></script>
+  </head>
+  <body>
+    <div id="root"></div>
+    <script type="text/babel">
+      function App() {
+        // 需要 我们自己创建一个对象(ref对象 ==> {current: 组件实例}) 和 要获取的组件 建立ref绑定关系
+        const counterRef = React.createRef();
+        const inputRef = React.createRef();
+        return (
+          <div className="app">
+            <button
+              onClick={() => {
+                console.log(`output->counterRef`, counterRef);
+                console.log(`output->inputRef`, inputRef);
+              }}
+            >
+              获取Counter组件实例
+            </button>
+            <input type="text" ref={inputRef} />
+            {/*通过组件元素的ref属性 和 上面创建的ref对象 建立绑定关系*/}
+            <Counter ref={counterRef} />
+          </div>
+        );
+      }
+
+      class Counter extends React.Component {
+        constructor(props) {
+          super(props);
+
+          this.state = {
+            c: 0,
+          };
+
+          this.handleAddOne = this.handleAddOne.bind(this);
+        }
+
+        handleAddOne() {
+          // this
+          // ? this.state.c 是上一次状态吗。不一定。因为 setState状态的更新 可能是异步的
+          // 如果当前新状态 的值 需要依赖 上一次状态的值 运算才能计算出 这个时候 就不能像下面方式写
+          // this.setState({ c: this.state.c + 1 });
+          // 为了 准确获取上一次状态 可以给 setState方法 传入一个回调函数:该函数会接收两个参数:prevState、props。传入的回调函数 在返回一个新的状态对象即可
+          this.setState((prevState) => {
+            return { c: prevState.c + 1 };
+          });
+        }
+
+        render() {
+          let { c } = this.state;
+          return (
+            <div className="counter">
+              <p>当前计数:{c}</p>
+              <p>
+                <button
+                  onClick={() => {
+                    // this
+                    this.setState(({ c }) => ({ c: c - 1 }));
+                  }}
+                >
+                  -
+                </button>
+                <button onClick={this.handleAddOne}>+</button>
+              </p>
+            </div>
+          );
+        }
+      }
+
+      const root = ReactDOM.createRoot(document.querySelector('#root'));
+
+      root.render(<App />);
+    </script>
+  </body>
+</html>