【React 資料備份】React Hook

Hooks是React16.8一個新增項,是咱們能夠不用建立class組件就能使用狀態和其餘React特性html

準備工做

  • 升級react、react-domreact

    npm i react react-dom -S

狀態鉤子 State Hook

  • 建立HooksTest.jsnpm

    import React, { useState } from "react";
    
    export default function HooksTest() {
      // useState(initialState),接收初始狀態,返回一個狀態變量和其更新函數
      const [count, setCount] = useState(0);
      return (
        <div>
          <p>You clicked {count} times</p>
          <button onClick={() => setCount(count + 1)}>Click me</button>
        </div>
      );
    }

    更新函數相似setState,但它不會整合新舊狀態bash

  • 聲明多個狀態變量dom

    export default function HooksTest() {
      const [age, setAge] = useState(42);
      const [fruit, setFruit] = useState('banana');
      const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
      return (
        <div>
          <p>年齡 {age}</p>
          <p>水果 {fruit}</p>
          <ul>
              {todos.map(todo=><li key={todo.text}>{todo.text}</li>)}
          </ul>
        </div>
      );
    }

反作用鉤子 Effect Hook

  • 更新HooksTest.js函數

    import React, { useState, useEffect } from "react";
    useEffect(() => {
      // Update the document title using the browser API
        document.title = `您點擊了 ${count} 次`;
    });
相關文章
相關標籤/搜索