Hooks是React16.8一個新增項,是咱們能夠不用建立class組件就能使用狀態和其餘React特性html
升級react、react-domreact
npm i react react-dom -S
建立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> ); }
更新HooksTest.js函數
import React, { useState, useEffect } from "react"; useEffect(() => { // Update the document title using the browser API document.title = `您點擊了 ${count} 次`; });