Este es mi código:
<div onClick={(e) => handleClick()}>Join Us</div>Esto es handleclick:
const handleClick = () => { console.log(Lang.getLocale()) };Y esta es mi función:
class Lang { static getLocale() { const { locale } = useRouter(); return locale?.toString() } } export default LangPero me sale este error:
react-dom.development.js?ac89:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. You might have mismatching versions of React and the renderer (such as React DOM) 2. You might be breaking the Rules of Hooks 3. You might have more than one copy of React in the same app See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.El error se describe a sí mismo, solo puede llamar a ganchos en el cuerpo de los componentes funcionales, porque los ganchos están destinados a engancharse en el ciclo de vida de un componente. Entonces, si desea crear sus propios ayudantes de Lang usando ganchos, su Lang debe ser un gancho useLang
function useLang(){ const { locale } = useRouter(); const getLocale = React.useCallback(() => locale.toString(), [locale]); const setLocale = React.useCallback(l => { // some logic to update locale}, []); return { getLocale, setLocale } }Así funcionan los anzuelos, extender los anzuelos se hace envolviéndolos en otros anzuelos.