source

리액트 라우터에서 일반 앵커링크를 사용하는 방법

itover 2023. 3. 28. 21:41
반응형

리액트 라우터에서 일반 앵커링크를 사용하는 방법

리액트 라우터를 사용할 때 페이지 내 네비게이션에 앵커링크를 사용하는 방법은 다음과 같습니다.

즉, 리액트 라우터를 사용할 때 다음과 같은 플레인 HTML을 구현하려면 어떻게 해야 합니까?

<a href="#faq-1">Question 1</a>
<a href="#faq-2">Question 2</a>
<a href="#faq-3">Question 3</a>

<h3 id="faq-1">Question 1</h3>
<h3 id="faq-2">Question 2</h3>
<h3 id="fa1-3">Question 3</h3>

현재 이러한 링크의 클릭을 대행 수신하여 앵커 위치까지 스크롤합니다.이는 페이지의 일부 섹션에 직접 연결할 수 없음을 의미하기 때문에 만족스럽지 않습니다.

앵커 링크의 문제는 리액트라우터의 디폴트로는 URL 내의 해시를 사용하여 상태를 유지하는 것입니다.다행히 위치 설명서에 따라 기본 동작을 다른 동작과 바꿀 수 있습니다.이 경우 HistoryLocation 개체를 사용하여 "clean URLs"를 시도해 볼 수 있습니다.즉, 리액트 라우터는 URL 해시를 사용하지 않습니다.다음과 같이 시험해 보십시오.

Router.run(routes, Router.HistoryLocation, function (Handler) {
  React.render(<Handler/>, document.body);
});

리액트 라우터 해시 링크가 작동했습니다.설치 및 구현이 용이함:

$ npm install --save react-router-hash-link

component.js에서 Link로 Import합니다.

import { HashLink as Link } from 'react-router-hash-link';

그리고 닻을 사용하는 대신<a>,사용하다<Link> :

<Link to="#faq-1>Question 1</Link>
<Link to="#faq-2>Question 2</Link>
<Link to="#faq-3>Question 3</Link>

주의: 사용하였습니다.HashRouter대신Router

import { Link } from 'react-router-dom'

링크 방법

<Link to='/homepage#faq-1'>Question 1</Link>

그런 다음 대상 React 구성 요소(홈 페이지)에 다음 코드를 삽입합니다.

useEffect(() => {
    const hash = props.history.location.hash
    // Check if there is a hash and if an element with that id exists
    const el = hash && document.getElementById(hash.substr(1))
    if (el) {    
        el.scrollIntoView({behavior: "smooth"})
    }
}, [props.history.location.hash]) // Fires every time hash changes

현재 사용 중인 방법 사용Link부터react-router-dom

<a href="#faq-1">Question 1</a>

로 달성할 수 있을 것이다

import React from 'react';
import {Link} from 'react-router-dom';

및 사용

<Link to={{pathname: '/this-view-path', hash: '#faq-1'}}>Question 1</Link>

물론 '/this-view-path'는 프로젝트의 변수로 제공될 수 있습니다.

라우터 6 의 경우는, 다음의 것을 사용할 수 있습니다.

const {hash, key} = useLocation()
useEffect(()=>{
    if(hash){
       const targetElement = document.getElementById(hash.substring(1))
        targetElement?.scrollIntoView({behavior: 'smooth'})
    }
}, [key, hash])

언급URL : https://stackoverflow.com/questions/28893855/how-to-use-normal-anchor-links-with-react-router

반응형