在React的函数式组件时代,Hooks成为了开辟者们弗成或缺的东西。它们容许我们以申明式的方法在函数组件中增加状况、处理反感化等。控制React Hooks,将极大年夜地晋升你的前端开辟才能,解锁新的开辟地步。
React Hooks是React 16.8版本引入的新特点,它们容许我们在不编写类的情况下利用state跟other React features。Hooks的呈现,使得函数组件可能拥有类组件的很多才能,同时也使得组件的编写愈加简洁。
useState是React中最基本的Hook,用于在函数组件中增加状况。
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useEffect用于处理反感化,如数据获取、订阅或手动变动React组件以外的DOM。
import React, { useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]); // 依附项数组,只有count变更时才履行反感化
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
useContext容许我们读取context的值,而不必在每一层组件上手动增加props。
import React, { useContext } from 'react';
import { ThemeContext } from './ThemeContext';
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button style={{ background: theme.background }}>{theme.text}</button>;
}
useReducer容许我们利用reducer函数来管理组件的状况。
import React, { useReducer } from 'react';
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<div>
<p>You clicked {state.count} times</p>
<button onClick={() => dispatch({ type: 'increment' })}>Increment</button>
<button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button>
</div>
);
}
useRef用于在组件的全部生命周期中持有一个可变的引用。
import React, { useRef } from 'react';
function Counter() {
const inputEl = useRef(null);
const focusInput = () => {
inputEl.current.focus();
};
return (
<div>
<input ref={inputEl} type="text" />
<button onClick={focusInput}>Focus the input</button>
</div>
);
}
React Hooks为函数组件供给了富强的功能,使得函数组件可能拥有类组件的很多才能。控制React Hooks,将极大年夜地晋升你的前端开辟才能,解锁新的开辟地步。