hooks
封装自定义hook通用思路
// 2.在函数体内封装可复用的逻辑(只要是可复用的逻辑)
// 3.把组件中用到的状态或者回调return出去(以对象或者数组)
// 4.在哪个组件中要用到这个逻辑,就执行这个函数,解构出来状态和回调进行使用
javascript
import { useState } from "react";
function Son() {
return <div>son组件</div>;
}
// 自定义hooks
// 注意函数的写法为匿名函数还是声明函数
function useTaggle() {
const [Show, setShow] = useState(true);
function taggle (){setShow(!Show)}
return {
Show,
taggle,
};
}
function App() {
// 在组件中使用需要进行结构
const { Show, taggle } = useTaggle();
// const [Show, setShow] = useState(true);
// const taggle=setShow(!Show)
return (
<div className="App">
{Show && <Son></Son>}
<button onClick={taggle}>卸载组件</button>
</div>
);
}
export default App;
使用规则
只能在组件中或者其他自定义HOOK函数中使用
只能在组件的顶层调用 不能在if for 其他函数中使用