告别useState去设置状态
原来写法
javascript
import React from 'react';
import { useState } from 'ahooks';
export default () => {
const [state, setState] = useState (false);
return (
<div>
<p>Effects:{`${state}`}</p>
<button type="button" onClick={()=> setState(!state)}>
State
</button>
</div>
);
};
useToggle
用于在两个状态值间切换的 Hook
。
代码演示
javascript
import React from 'react';
import { useToggle } from 'ahooks';
export default () => {
const [state, { toggle, setLeft, setRight }] = useToggle();
return (
<div>
<p>Effects:{`${state}`}</p>
<p>
<button type="button" onClick={toggle}>
Toggle
</button>
<button type="button" onClick={setLeft} style={{ margin: '0 8px' }}>
Toggle False
</button>
<button type="button" onClick={setRight}>
Toggle True
</button>
</p>
</div>
);
};
其中:
state
: 表示状态值
toggle, setLeft, setRight
: 分别表示切换状态值的方法
useToggle:hooks
,也会有默认值或者两个值进行切换
javascript
import React from 'react';
import { useToggle } from 'ahooks';
export default () => {
const [state, { toggle, set, setLeft, setRight }] = useToggle('Hello', 'World');
return (
<div>
<p>Effects:{state}</p>
<p>
<button type="button" onClick={toggle}>
Toggle
</button>
<button type="button" onClick={() => set('Hello')} style={{ margin: '0 8px' }}>
Set Hello
</button>
<button type="button" onClick={() => set('World')}>
Set World
</button>
<button type="button" onClick={setLeft} style={{ margin: '0 8px' }}>
Set Left
</button>
<button type="button" onClick={setRight}>
Set Right
</button>
</p>
</div>
);
};