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中文网其他相关文章!