react 组件 封装成hook
时间: 2023-07-01 07:04:50 浏览: 178
Reacthook用于在组件中使用键盘快捷键。_TypeScript_JavaScript_下载.zip
将 React 组件封装成 Hook 可以让我们更方便地在函数组件中复用组件逻辑。下面是一些封装组件为 Hook 的示例代码:
1. 使用 useState 封装计数器组件:
```javascript
import { useState } from 'react';
const useCounter = (initialCount = 0, step = 1) => {
const [count, setCount] = useState(initialCount);
const increment = () => setCount(count + step);
const decrement = () => setCount(count - step);
return { count, increment, decrement };
};
export default useCounter;
```
使用示例:
```javascript
import useCounter from './useCounter';
function Counter() {
const { count, increment, decrement } = useCounter();
return (
<>
<p>Count: {count}</p>
<button onClick={increment}>+</button>
<button onClick={decrement}>-</button>
</>
);
}
```
2. 使用 useEffect 封装鼠标位置跟踪组件:
```javascript
import { useState, useEffect } from 'react';
const useMousePosition = () => {
const [position, setPosition] = useState({ x: 0, y: 0 });
useEffect(() => {
const updateMousePosition = (event) => {
setPosition({ x: event.clientX, y: event.clientY });
};
document.addEventListener('mousemove', updateMousePosition);
return () => {
document.removeEventListener('mousemove', updateMousePosition);
};
}, []);
return position;
};
export default useMousePosition;
```
使用示例:
```javascript
import useMousePosition from './useMousePosition';
function MouseTracker() {
const { x, y } = useMousePosition();
return (
<p>
Mouse position: {x}, {y}
</p>
);
}
```
以上是两个简单的示例,通过封装 React 组件为 Hook,可以让我们更好地复用组件逻辑并在函数组件中使用。
阅读全文