// 问题:当前组件耦合在一起的不方便复用
// 解决思路:自定义hook
// 1。封装use打头的函数
// 2.在函数体内封装我们可复用的逻辑(只要是可复用的都行)
// 3.要把组件中用到的状态(变量)或者回调return出去
// 4.在哪个组件中用到这个逻辑,引用这个函数,然后解构出来返回值
import { useEffect, useState } from "react";
// 可复用的逻辑代码
function useTottle(){
// 可复用的代码
const [value,setValue]=useState(true);
const toger=()=> setValue(!value);
// 那些状态和回调函数需要在其他组件中使用 return 出去
return { value,toger}
}
function App() {
const { value,toger}= useTottle();
return (
<div className="App">
{value&& <div>显示了</div>}
<button onClick={toger}>显示和隐藏</button>
</div>
);
}
export default App;
react 自定义Hook的实现
于 2024-06-15 18:01:25 首次发布