这是我的自定义组件。基本上,它是显示api调用失败或成功的模式。
export const useMessageModal = () => {
const [IsModalVisible, setIsModalVisible] = useState(false);
const [Message, setMessage] = useState(null);
return [
() =>
IsModalVisible ? (
<CModal
isVisible={IsModalVisible}
modalMsg={Message}
onPressModal={() => setIsModalVisible(false)} //hideModal
/>
) : null,
() => setIsModalVisible(true), //showModal
msg => setMessage(msg),
];
};
在其中一个组件中,我想导航到另一页或在模式按钮上调用一些上下文动作,以便将某些功能传递给此自定义钩子。 有人知道吗?
根据Shubham Verma的回答,我已经更新了代码
import React, { useState, useEffect } from "react";
import "./styles.css";
const CModal = ({ onPressModal }) => {
return (
<div
onClick={() => {
console.log("TEst");
onPressModal();
}}
>
Click me to check function call(open console)
</div>
);
};
export const useMessageModal = (customFuntion) => {
const [IsModalVisible, setIsModalVisible] = useState(false);
const [Message, setMessage] = useState(null);
return [
() =>
IsModalVisible ? (
<CModal
isVisible={IsModalVisible}
modalMsg={Message}
onPressModal={customFuntion} //hideModal
/>
) : null,
() => setIsModalVisible(true), //showModal
(msg) => setMessage(msg)
];
};
export default function App() {
const [test2, setTest2] = useState(false);
const [test, check] = useMessageModal(
() => (test2 ? console.log("gjghjgj") : console.log("hello")),
[test2]
);
useEffect(() => {
check();
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<button onClick={() => [console.log(test2), setTest2(!test2)]}>
test
</button>
{test()}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
答案 0 :(得分:0)
您可以简单地将功能作为论点useMessageModal
传递。这是poc:
import React, { useState, useEffect } from "react";
import "./styles.css";
const CModal = ({ onPressModal }) => {
return (
<div
onClick={() => {
console.log("TEst");
onPressModal();
}}
>
Click me to check function call(open console)
</div>
);
};
export const useMessageModal = (customFuntion) => {
const [IsModalVisible, setIsModalVisible] = useState(false);
const [Message, setMessage] = useState(null);
return [
() =>
IsModalVisible ? (
<CModal
isVisible={IsModalVisible}
modalMsg={Message}
onPressModal={customFuntion} //hideModal
/>
) : null,
() => setIsModalVisible(true), //showModal
(msg) => setMessage(msg)
];
};
export default function App() {
const [test, check, anotherCheck] = useMessageModal(() =>
console.log("hello")
);
useEffect(() => {
check();
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{test()}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
以下是演示:https://codesandbox.io/s/custom-hook-function-37kc8?file=/src/App.js