自定义 Hook
一句话解释
自定义 Hook 是用户-定义函数开始使用 'use' 那个 extracts and reuses stateful logic 跨越组件.
用大白话说
自定义 Hook 是 JavaScript 函数谁的 name 开始使用 use and that can call other Hooks inside it. It lets you extract component logic into a reusable function, just like you extract JSX into a component.
For example, a useWindowWidth() Hook could encapsulate the logic for tracking the browser window width. Any component can call const width = useWindowWidth() and get the current width, with all the event listener setup and cleanup hidden inside the Hook.
Custom Hooks are the primary way to share stateful logic in modern React. They replaced higher-order components and render props patterns. The naming convention (use...) is required so React's linter can enforce the Rules of Hooks.
示例
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handler = () => setWidth(window.innerWidth);
window.addEventListener("resize", handler);
return () => window.removeEventListener("resize", handler);
}, []);
return width;
}
// Use it anywhere
function MyComponent() {
const width = useWindowWidth();
return <p>Window is {width}px wide</p>;
}useWindowWidth encapsulates resize 监听器 and 状态. 任何组件能 call 它到 获取 current window 宽度.
相关术语
相关资源
相关课程
- 自定义 Hook
学习到 构建 and reuse 自定义 Hook.
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。