Browse Source

react:study2

e 1 year ago
parent
commit
93c95ec484
2 changed files with 49 additions and 8 deletions
  1. 1 1
      react/study2/4.事件处理.html
  2. 48 7
      react/study2/8.state.html

+ 1 - 1
react/study2/4.事件处理.html

@@ -56,7 +56,7 @@
                     {/*
                         传递多个参数时 接收参数需要解构
                     */}
-                    <p onClick={handleClick3.bind(null,44)}>事件3</p>
+                    <p onClick={handleClick3.bind(null,44,55)}>事件3</p>
                     {/* null不占位 */}
                     
                 </div>

+ 48 - 7
react/study2/8.state.html

@@ -1,16 +1,57 @@
 <!DOCTYPE html>
 <html lang="en">
-<head>
-    <meta charset="UTF-8">
-    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+  <head>
+    <meta charset="UTF-8" />
+    <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>
+  </head>
+  <body>
     <div id="root"></div>
     <script type="text/babel">
+      // 类组件 state 可以修改数据
+      // 计数器
+      class White extends React.Component {
+        // 定义初始数值
+        state = {
+          title: "计数器",
+          count: 0,
+        };
+        // constructor() {
+        //     super(props),
+        //     state={
+        //     }
+        // }
+        // 数据更新视图未变
+        // vue解决方案:Vue.set() this.$set
+        // react解决方案:
+        handleAdd() {
+          this.setState({
+            count: this.state.count + 1,
+          });
+          console.log(this.state, "加法");
+        }
+        handleReduce = () => {
+            console.log(this)
+          this.setState({
+            count: this.state.count - 1,
+          });
+        };
+        render() {
+          return (
+            <div>
+              <h2>{this.state.title}</h2>
+              <p>当前数值:{this.state.count}</p>
+              <button onClick={this.handleAdd.bind(this)}>+</button>
+              <button onClick={this.handleReduce}>-</button>
+            </div>
+          );
+        }
+      }
+      let element = <White />;
+      ReactDOM.createRoot(document.querySelector("#root")).render(element);
     </script>
-</body>
-</html>
+  </body>
+</html>