EDIT: ustawiłem kod pola: https://codesandbox.io/s/magical-poitras-yogur?file=/src/App.tsx
Próbuję stworzyć własny hak do elementu div w react, aby dodać detektory zdarzeń.
Znalazłem to "całkowita" rozwiązanie:
function useMyCustomHook<T extends HTMLElement>{
const myRef = useRef<T>(null)
// do something with the ref, e.g. adding event listeners
return {ref: myRef}
}
function MyComponent(){
const {ref: myElementRef} = useMyCustomHook<HTMLDivElement>()
return <div ref={myElementRef}>A Div</div>
}
Który starałem się realizować w swoim kodzie poniżej. Grałem przez kilka godzin i w końcu doprowadził wszystko do jednego błędu, ale nie wiem jak go rozwiązać. Błąd w moim useHover
wyrażenie funkcji na pierwszym =
. błąd polega na: '(' expected.ts(1005)
teraz mój kod:
const Hooks = (props: any) => {
const [hoverRef, hovered] = useHover();
const style = {
backgroundColor: hovered ? "red" : "",
};
return (
<div ref={hoverRef} style={style}>
<h1>Hooks!</h1>
</div>
);
};
const useHover:<HTMLDivElement extends HTMLElement> = () => {
// ERROR HERE ^ the first equal sign. '(' expected.ts(1005)
const [value, setValue] = useState(false);
const ref = useRef<HTMLDivElement>(null);
const handleMouseOver = () => setValue(true);
useEffect(() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseover", handleMouseOver);
return () => {
node.removeEventListener("mouseover", handleMouseOver);
}
}
}, []);
return [ref, value];
};
Każda pomoc będzie wdzięczna!