타이프 라이터는 반응을 주문 걸이 ref div 요소

0

질문

편집:나는 설정 codesandbox: https://codesandbox.io/s/magical-poitras-yogur?file=/src/App.tsx

내가 만들려고 노력하는 사용자 정의 후크를 div 요소에 대응하는 이벤트 리스너를 추가.

내가 찾은 이를'일반'솔루션:

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>
}

에서: 할당할 수 없습니다 RefObject<HTMLDivElement>을 RefObject<HTMLElement>인스턴스

는 해봤을 구현하는 내 아래 코드. 연주했는데 주위를 위해 시간 및 마지막으로 가지고 그것만이 하나 오류를 모르겠지만 그것을 해결하는 방법. 에 오류가 나 useHover 기능 표현에서 첫번째 =. 오류 메시지는 다음과 같습니다. '(' expected.ts(1005)

내 코드는 지금:

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];
};

어떤 도움에 감사드립니다!

react-hooks reactjs typescript
2021-11-24 05:57:28
1

최고의 응답

1

이것을 보십시오:사용하는 대신 ref 고 명령적으로 조작하는 기본 DOM 이벤트를 만들 요소 속성에 대한 이벤트를 처리할 돌아와 그와 함께 사용하의 반응하는 요소:

참고:당신은 무시할 수 있습니다 CSS 첫 번째 네 <script> 요소들(그들은 그냥 거기에 그렇게는 타이프 라이터 구문을 반응에서 작동 조각모).

body {
  font-family: sans-serif;
}

.target {
  border: 1px solid;
  padding: 1rem;
}
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
<script>Babel.registerPreset('tsx', {presets: [[Babel.availablePresets['typescript'], {allExtensions: true, isTSX: true}]]});</script>

<div id="root"></div>

<script type="text/babel" data-type="module" data-presets="tsx,react">

/**
 * The following line is here because this Stack Overflow snippet uses the
 * UMD module for React. In your code, you'd use the commented `import` lines
 * below it.
 */
const {useMemo, useState} = React;

// import {useMemo, useState} from 'react';
// import type {DetailedHTMLProps, HTMLAttributes, ReactElement} from 'react';

type HoverData<T extends HTMLElement> = {
  hoverProps: DetailedHTMLProps<HTMLAttributes<T>, T>;
  isHovered: boolean;
};

function useHover <T extends HTMLElement>(): HoverData<T> {
  const [isHovered, setIsHovered] = useState(false);

  const hoverProps: HoverData<T>['hoverProps'] = useMemo(() => ({
    onMouseEnter: () => setIsHovered(true),
    onMouseLeave: () => setIsHovered(false),
  }), [setIsHovered]);

  return {hoverProps, isHovered};
}

function Example (): ReactElement {
  const {hoverProps, isHovered} = useHover<HTMLDivElement>();

  return (
    <div>
      <h1>Hover the text below</h1>
      <div {...hoverProps} className="target">
        {isHovered ? 'Now move it away' : 'Move pointer here'}
      </div>
    </div>
  );
}

ReactDOM.render(<Example />, document.getElementById('root'));

</script>

2021-11-29 06:48:48

다른 언어로

이 페이지는 다른 언어로되어 있습니다

Русский
..................................................................................................................
Italiano
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................