自定义 Hook 的封装原则
组件=页面 UI
Hook=逻辑工具
原则 1:必须以 use 开头
原则 2:只复用逻辑,不写 UI
原则 3:通过参数输入,通过 return 输出
原则 4:返回数据、状态和方法
function useCounter() {
const [count, setCount] = useState(0);
const add = () => setCount(count + 1);
const minus = () => setCount(count - 1);
return { count, add, minus };
}
function App() {
const { count, add, minus } = useCounter();
return (
<div>
<p>{count}</p>
<button onClick={add}>+</button>
<button onClick={minus}>-</button>
</div>
);
}
