Browse Source

react_study4

siwat 1 năm trước cách đây
mục cha
commit
c64b7fac48

+ 38 - 0
xiangminmin/react/syudy4/src/App.css

@@ -0,0 +1,38 @@
+.App {
+  text-align: center;
+}
+
+.App-logo {
+  height: 40vmin;
+  pointer-events: none;
+}
+
+@media (prefers-reduced-motion: no-preference) {
+  .App-logo {
+    animation: App-logo-spin infinite 20s linear;
+  }
+}
+
+.App-header {
+  background-color: #282c34;
+  min-height: 100vh;
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  justify-content: center;
+  font-size: calc(10px + 2vmin);
+  color: white;
+}
+
+.App-link {
+  color: #61dafb;
+}
+
+@keyframes App-logo-spin {
+  from {
+    transform: rotate(0deg);
+  }
+  to {
+    transform: rotate(360deg);
+  }
+}

+ 29 - 0
xiangminmin/react/syudy4/src/App.js

@@ -0,0 +1,29 @@
+import './App.css';
+import Time from "./components/1_LifeCycle";
+import Table from "./components/2_Table";
+import Demo from "./components/3_Hooks_useState"
+import Count from "./components/4_Count"
+import Effect from "./components/5_Hooks_useEffect"
+// import {Clock} from "./components/6_Clock"
+import {Clock} from "./components/6_Clock"
+import Memo from './components/7_Hooks_useMemo';
+import Back from './components/8_Hooks_useCallBack';
+
+function App() {
+  return (
+    <div className="App">
+      <header className="App-header">
+        {/* <Time />
+        <Table />
+        <Demo />
+        <Count />
+        <Effect /> */}
+        {/* <Clock Beijing="现在是北京时间"/> */}
+        {/* <Memo /> */}
+        <Back />
+      </header>
+    </div>
+  );
+}
+
+export default App;

+ 8 - 0
xiangminmin/react/syudy4/src/App.test.js

@@ -0,0 +1,8 @@
+import { render, screen } from '@testing-library/react';
+import App from './App';
+
+test('renders learn react link', () => {
+  render(<App />);
+  const linkElement = screen.getByText(/learn react/i);
+  expect(linkElement).toBeInTheDocument();
+});

+ 65 - 0
xiangminmin/react/syudy4/src/components/1_LifeCycle.jsx

@@ -0,0 +1,65 @@
+import { Component } from "react";
+
+class Time extends Component{
+    state = {
+        time: new Date(),
+        timer:null
+    }
+
+    // 生命周期
+    // 挂载后
+    componentDidMount(){
+        this.start()
+    }
+    // 更新后
+    componentDidUpdate(){
+        // console.log("更新了")
+    }
+    // 卸载前
+    componentWillUnmount(){
+        this.stop()
+    }
+
+    // 开始计时
+    start(){
+        let nowTime;
+        let timerA;
+        this.timer = timerA =  setInterval(()=>{
+            nowTime = new Date()
+            this.setState({
+                time:nowTime,
+                timer:timerA
+            })
+        },1000)
+    }   
+    // 暂停计时
+    stop(){
+        clearInterval(this.state.timer)
+        this.setState({
+            timer:null
+        })
+    }
+
+    handlerTime = ()=>{
+        if(this.state.timer)
+            this.stop()
+        else
+            this.start()
+    }
+    render(){
+        return(
+            <div>
+                <h3>当前时间是:{this.state.time.toLocaleString()}</h3>
+                {/* <button onClick = {this.stop.bind(this)}>
+                    {console.log(this)}
+                    {this.state.timer?"暂停":"开始"}
+                </button> */}
+                <button onClick = {this.handlerTime}>
+                    {this.state.timer?"暂停":"开始"}
+                </button>
+            </div>
+        )
+    }
+}
+
+export default Time;

+ 9 - 0
xiangminmin/react/syudy4/src/components/2_Table.css

@@ -0,0 +1,9 @@
+.table{
+    border: 1px solid #eee;
+    border-collapse: collapse;
+    margin-top: 50px;
+}
+.table td, .table th{
+    border: 1px solid #eee;
+    padding: 10px;
+}

+ 87 - 0
xiangminmin/react/syudy4/src/components/2_Table.jsx

@@ -0,0 +1,87 @@
+import { Component } from "react";
+import "./2_Table.css"
+class Table extends Component{
+    state = {
+        date:[
+            {
+                score:[70,60,30],
+                bonus:300,
+                name:"小明"
+            },
+            {
+                score:[90,160,80],
+                bonus:500,
+                name:"小栗"
+            },
+            {
+                score:[60,95,95],
+                bonus:200,
+                name:"小红"
+            },
+            {
+                score:[100,100,100],
+                bonus:400,
+                name:"小白"
+            }
+        ]
+    };
+
+    // 数据根据奖金降序排列
+    sortDate(){
+        return this.state.date.sort((a,b)=>b.bonus-a.bonus)
+    }
+    // 渲染内容
+    newTable(){
+        var newDate = this.sortDate()
+
+        return newDate.map((item,index)=>{
+            return (
+                <tr key={index}>
+                    <td>{index+1}</td>
+                    <td>{item.name}</td>
+                    {item.score.map((item,index) => <td key={index}>{item}</td>)}
+                     {/* reduce 数据的累加或累减
+                         第一个参数:总数=>total
+                         第二个参数:当前元素=>currentValue
+                    */}
+                    <td>{item.score.reduce((c,d)=> c+d)}</td>
+                    <td>{item.bonus}</td>
+                </tr>
+            )
+        })
+    }
+    render(){
+        return (
+            <div>
+                <table className="table">
+                    <thead>
+                        <tr>
+                            <th>名次</th>
+                            <th>名字</th>
+                            <th colSpan={3}>分 数</th>
+                            <th>总分</th>
+                            <th>奖金</th>
+                        </tr>
+                        {this.newTable()}
+                        <tr>
+                            <td colSpan={6}>奖金总计</td>
+                            <td>{this.state.date.reduce((x,y)=> x+y.bonus,0)}</td>
+                        </tr>
+                    </thead>
+                    <tbody>
+                        {/* <tr>
+                            <td>第一名</td>
+                            <td>best</td>
+                            <td>98</td>
+                            <td>76</td>
+                            <td>88</td>
+                            <td>262</td>
+                            <td>500</td>
+                        </tr> */}
+                    </tbody>
+                </table>
+            </div>
+        )
+    }
+}
+export default Table;

+ 49 - 0
xiangminmin/react/syudy4/src/components/3_Hooks_useState.jsx

@@ -0,0 +1,49 @@
+// Hooks 是16.8版本新增的一个钩子, 主要解决:函数组件中数据无法修改的问题
+// 使用哪个钩子,就要在函数组件中导入哪个钩子
+import { useState } from 'react';
+
+// function Demo(){
+    // hooks钩子要写在函数组件的顶部
+    // 可以定义多个钩子
+    // useState(初始值)
+    // let [name,setName] = useState("糯米")
+    // let [age,setAge] = useState(18)
+    // let [address,setAddress] = useState("北京")
+
+    // 修改值可使用对应的 setxxx("新值")
+    // let change = ()=>{
+    //     setName("栗子")
+    //     setAge(20)
+    //     setAddress("上海")
+    //     console.log(this)
+    // }
+//     function change(){
+//         setName("栗子")
+//         setAge(20)
+//         setAddress("上海")
+//         console.log(this)
+//     }
+//     return(
+//         <div>
+//             <p>我是 {name},今年 {age}岁,我住在 {address}</p>
+//             <button onClick ={change.bind(this)}>修改</button>
+//         </div>
+//     )
+// }
+
+function Demo(){
+    let [user,setUser] = useState({
+        name:"糯米",
+        age:18
+    })
+    return(
+        <div>
+            <p>我是 {user.name},今年 {user.age}岁</p>
+            <button onClick ={()=>{
+                // 修改对象的值,要使用对象的解构赋值
+                setUser({...user,name:"栗子",age:20})
+            }}>修改</button>
+        </div>
+    )
+}
+export default Demo;

+ 31 - 0
xiangminmin/react/syudy4/src/components/4_Count.jsx

@@ -0,0 +1,31 @@
+import { useState } from "react";
+
+function Count(){
+    let [count,setCount] = useState(0)
+
+    function add(){
+        setCount(count+1)
+    }
+
+    function reduce(){
+        setCount(count-1)
+    }
+
+    return(
+        <div>
+            <h3>计数器</h3>
+            <p>{count}</p>
+            <button onClick={add}>+1</button><br/>
+            <button onClick={reduce}>-1</button><br/>
+            <button onClick={()=>{
+                setCount((a)=>a+1)
+                setCount((a)=>a+1)
+                setCount((a)=>a+1)
+                setCount((a)=>a+1)
+                setCount((a)=>a+1)
+            }}>+5</button>
+        </div>
+    )
+
+}
+export default Count;

+ 54 - 0
xiangminmin/react/syudy4/src/components/5_Hooks_useEffect.jsx

@@ -0,0 +1,54 @@
+import { useEffect, useState } from "react";
+
+function Test({name,age}){
+    // 用法 3. 组建卸载前执行
+    // 处理一些冗余
+    useEffect(()=>{
+        return(
+            console.log("即将卸载组建")
+        )
+    },[])
+
+    return(
+        <div>
+            <p>我的名字:{name}</p>
+            <p>我的年龄:{age}</p>
+        </div>
+    )
+}
+
+function Effect({name=" "}){
+    let [msg,setMsg] = useState("这是一条消息")
+
+    // 用法 1. useEffect(()=>{})
+    // 每次组件渲染时都会调用 执行一些副作用代码
+    // useEffect(()=>{
+    //     console.log("副作用代码")
+    // })
+
+    // 用法 2. useEffect(()=>{},[])
+    // 最主要的是第二个参数是空数组[] , 模拟生命周期 componentDidMount 挂载后调用
+    // useEffect(()=>{
+    //     console.log("模拟生命周期 componentDidMount 挂载前后调用")
+    // },[])
+
+    // 用法 4. useEffect(()=>{},[n])
+    // 监听 state 或者 props 发生变化 (组建初次渲染也会发生监听事件)
+    useEffect(()=>{
+        console.log("信息发生变化")
+    },[msg,name])
+
+    return(
+        <div>
+            <h3>useEffect</h3>
+            <p>{msg}</p>
+            <p>名字:{name}</p>
+            <Test name={"Best"} age={17}/>
+            <button onClick={()=>{
+                setMsg("这是修改后的msg")
+            }}>修改msg</button>
+        </div>
+    )
+}
+
+export default Effect;

+ 25 - 0
xiangminmin/react/syudy4/src/components/6_Clock.jsx

@@ -0,0 +1,25 @@
+import { useEffect, useState } from "react";
+
+// export default 默认抛出组建在引入时不可以使用 {} 包裹
+// 通过export方式导出,在导入时要加{ },export default则不需要
+export function Clock({Beijing}){
+
+    let [time,setTime] = useState(new Date())
+
+    useEffect(()=>{
+        let timer;
+        timer = setInterval(()=>{
+            setTime(new Date())
+        },1000)
+        return ()=>{
+            clearInterval(timer)
+        }
+    },[])
+
+    return(
+        <div>
+            <h4>我是Clock</h4>
+            <p>{Beijing || "当前时间"} : {time.toLocaleString()}</p>
+        </div>
+    )
+}

+ 22 - 0
xiangminmin/react/syudy4/src/components/7_Hooks_useMemo.jsx

@@ -0,0 +1,22 @@
+import { useMemo,useState } from "react";
+
+export default function Memo({name}){
+
+    let [Num,setNum] = useState(7)
+
+    // useMemo类似于Vue中的计算属性,缓存功效,缓存值
+    // useMemo(()=>{},[依赖项])
+    // 一定要判断场景 使用useMemo
+    // let newNum = useMemo(()=>Num+10,[Num])
+    let newNum = useMemo(()=>{
+        console.log('useMemo执行了');
+        return Num+10
+    },[Num])
+
+    return (
+        <div>
+            <h3>{newNum}</h3>
+            <p>{name}</p>
+        </div>
+    )
+}

+ 30 - 0
xiangminmin/react/syudy4/src/components/8_Hooks_useCallBack.jsx

@@ -0,0 +1,30 @@
+import { useCallback,useState,useEffect } from "react";
+// useCallback 用于缓存函数 
+// useCallback(()=>{},[])
+
+// 在react中 props中自带一个children属性用于接收组件标签中的内容
+function Test({children,onClick}){
+
+    useEffect(()=>{
+        console.log("组件发生改变")
+        // console.log(children)
+    })
+
+    return (
+        <button onClick={onClick}>{children}</button>
+    )
+}
+
+export default function Back(){
+
+    let [text,setText] = useState("这是文本")
+
+    const handlerClick = useCallback(()=>{setText("这是一条新文本")},[])
+
+    return(
+        <div>
+            <p>{text}</p>
+            <Test onClick={handlerClick}>修改内容</Test>
+        </div>
+    )
+}

+ 13 - 0
xiangminmin/react/syudy4/src/index.css

@@ -0,0 +1,13 @@
+body {
+  margin: 0;
+  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
+    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
+    sans-serif;
+  -webkit-font-smoothing: antialiased;
+  -moz-osx-font-smoothing: grayscale;
+}
+
+code {
+  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
+    monospace;
+}

+ 17 - 0
xiangminmin/react/syudy4/src/index.js

@@ -0,0 +1,17 @@
+import React from 'react';
+import ReactDOM from 'react-dom/client';
+import './index.css';
+import App from './App';
+import reportWebVitals from './reportWebVitals';
+
+const root = ReactDOM.createRoot(document.getElementById('root'));
+root.render(
+  <React.StrictMode>
+    <App />
+  </React.StrictMode>
+);
+
+// If you want to start measuring performance in your app, pass a function
+// to log results (for example: reportWebVitals(console.log))
+// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
+reportWebVitals();

Những thai đổi đã bị hủy bỏ vì nó quá lớn
+ 0 - 0
xiangminmin/react/syudy4/src/logo.svg


+ 13 - 0
xiangminmin/react/syudy4/src/reportWebVitals.js

@@ -0,0 +1,13 @@
+const reportWebVitals = onPerfEntry => {
+  if (onPerfEntry && onPerfEntry instanceof Function) {
+    import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => {
+      getCLS(onPerfEntry);
+      getFID(onPerfEntry);
+      getFCP(onPerfEntry);
+      getLCP(onPerfEntry);
+      getTTFB(onPerfEntry);
+    });
+  }
+};
+
+export default reportWebVitals;

+ 5 - 0
xiangminmin/react/syudy4/src/setupTests.js

@@ -0,0 +1,5 @@
+// jest-dom adds custom jest matchers for asserting on DOM nodes.
+// allows you to do things like:
+// expect(element).toHaveTextContent(/react/i)
+// learn more: https://github.com/testing-library/jest-dom
+import '@testing-library/jest-dom';

Một số tệp đã không được hiển thị bởi vì quá nhiều tập tin thay đổi trong này khác