React hooks 刚刚在上一个 React 版本中发布16.8.1
,提供了使用状态、效果和上下文的钩子。
如何构建自定义钩子?
正如反应文档中所说:
自定义 Hook 是一个 JavaScript 函数,其名称以“use”开头,并且可以调用其他 Hook。
所以通常你只需要创建另一个函数来调用你想要使用的钩子。我认为“use”前缀只是为了约定,但我无法确认。
例如,这个计数器是一个自定义钩子:
function useCounter(){
let [value, set] = useState(0);
return [
value,
// an increment function
() => set(value+1),
// feel free to add any other functions or datas you wish here
];
}
在组件中使用此计数器:
function MyComponent(){
// use of custom hook
let [count, increment] = useCounter();
return (
<div>
<div>Times clicked: {count}</div>
<button onClick={increment}>Click me</button>
</div>
);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句