React Hooks 是允許您在功能元件中使用狀態和其他 React 功能的函數,這些函數傳統上僅在類別元件中可用。它們在 React 16.8 中引入,並從此成為編寫 React 元件的標準。以下是最常用鉤子的細分:
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); // Declare a state variable called 'count' return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
import React, { useEffect, useState } from 'react'; function Example() { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty dependency array means this effect runs once after the initial render. return <div>{data ? data : 'Loading...'}</div>; }
import React, { useContext } from 'react'; const ThemeContext = React.createContext('light'); function DisplayTheme() { const theme = useContext(ThemeContext); // Access the current theme context value return <div>The current theme is {theme}</div>; }
import React, { useReducer } from 'react'; function reducer(state, action) { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> ); }
import React, { useRef, useEffect } from 'react'; function TextInputWithFocusButton() { const inputEl = useRef(null); const onButtonClick = () => { inputEl.current.focus(); // Access the DOM element directly }; return ( <> <input ref={inputEl} type="text" /> <button onClick={onButtonClick}>Focus the input</button> </> ); }
import React, { useMemo, useCallback } from 'react'; function Example({ items }) { const expensiveCalculation = useMemo(() => { return items.reduce((a, b) => a + b, 0); }, [items]); const memoizedCallback = useCallback(() => { console.log('This function is memoized'); }, []); return <div>{expensiveCalculation}</div>; }
Hooks 改變了開發人員編寫 React 應用程式的方式,使功能元件更強大且更易於管理。
以上是反應鉤子的詳細內容。更多資訊請關注PHP中文網其他相關文章!