反应挂钩导出功能
react hooks export functions
我正在尝试使用 ts 创建一个自定义挂钩,它将返回一个位于其中的函数,我尝试这样做的方式是:
export const useHook = () => {
const function1 = () => {
logic here
};
const function2=()=>{
logic here
}
return [function1,function2];
};
然后我尝试在这样的组件中使用它:
import { useHook } from "./connector/useHook";
function App() {
const {function1,function2} = useHook();
return (
<div>
<Home />
<button onClick={() => function1}>test</button>
<button onClick={() => function2}>test</button>
</div>
);
}
export default App;
但是我收到一条错误消息
Property 'function1' does not exist on type '(() => void)[]'.
const { function1, function2 } = useHook();
将 {}
替换为 []
,因为您正在 return 将其作为数组:
const [function1, function2] = useHook();
或 return 钩子中的一个对象:
export const useHook = () => {
const function1 = () => {
// logic here
};
const function2 = () => {
// logic here
};
return {function1, function2};
};
那么您可以将其用作:
cosnt {function1, function2} = useHook();
您已将函数作为数组 return [function1,function2];
返回。当你使用 like const {function1,function2} = useHook();
所以您可以使用两种方法
方法一:
Return 您的函数作为自定义挂钩的对象:
return { function1, function2 };
并像
一样使用它
const { function1, function2 } = useHook();
方法二:
Return 您的函数作为自定义挂钩的数组:
return [function1, function2];
并像
一样使用它
const [function1, function2] = useHook();
我正在尝试使用 ts 创建一个自定义挂钩,它将返回一个位于其中的函数,我尝试这样做的方式是:
export const useHook = () => {
const function1 = () => {
logic here
};
const function2=()=>{
logic here
}
return [function1,function2];
};
然后我尝试在这样的组件中使用它:
import { useHook } from "./connector/useHook";
function App() {
const {function1,function2} = useHook();
return (
<div>
<Home />
<button onClick={() => function1}>test</button>
<button onClick={() => function2}>test</button>
</div>
);
}
export default App;
但是我收到一条错误消息
Property 'function1' does not exist on type '(() => void)[]'.
const { function1, function2 } = useHook();
将 {}
替换为 []
,因为您正在 return 将其作为数组:
const [function1, function2] = useHook();
或 return 钩子中的一个对象:
export const useHook = () => {
const function1 = () => {
// logic here
};
const function2 = () => {
// logic here
};
return {function1, function2};
};
那么您可以将其用作:
cosnt {function1, function2} = useHook();
您已将函数作为数组 return [function1,function2];
返回。当你使用 like const {function1,function2} = useHook();
所以您可以使用两种方法
方法一:
Return 您的函数作为自定义挂钩的对象:
return { function1, function2 };
并像
一样使用它const { function1, function2 } = useHook();
方法二:
Return 您的函数作为自定义挂钩的数组:
return [function1, function2];
并像
一样使用它const [function1, function2] = useHook();