将钩子作为道具传递
将 React Hook 作为道具传递给另一个组件是否可以接受/常见?
或者它们是否意味着只属于它所声明的组件?
下面只是一个例子来说明我将它作为
道具从父组件传递给子父组件的意思。
import React, { useState } from 'react';
export const Parent = () => {
const [count, setCount] = useState(0);
return <div>
Current count is {count}
<Child setCount={setCount} /> // passing a hook set call as a prop to child
</div>
}
const Child = ({setCount}) => {
setCount(10) // using the hook set call
return (
<div>
Some Child Text
</div>
);
};
export default Child;
回答
setCount不是钩子,它只是另一个函数,所以你可以将它作为道具传递。您也可以考虑useEffector的输出useCallback,这些可以作为道具传递。useState是一个钩子,useCallback是一个钩子,甚至对于封装其他钩子的任何函数,这些都不应该作为道具传递。
为什么?
要回答这个问题,首先想一想为什么要将钩子作为道具传递?将钩子作为道具传递的好处是您可以有条件地传递另一个钩子/跳过调用。
但是在 hooks 的情况下,不应该有条件地调用它。所以没有意义。将它作为道具传递,只需导入并使用它。