programing

리액트 리액트 리액트 리액트 리액트 리액트:액티브한 경우 디세블로 하려면 어떻게 해야 하나요?

javamemo 2023. 3. 1. 08:46
반응형

리액트 리액트 리액트 리액트 리액트 리액트:액티브한 경우 디세블로 하려면 어떻게 해야 하나요?

디세블로 하려면 어떻게 해야 하나요?<Link>이 URL이 이미 활성화 되어 있는 경우, react-router로 설정합니다.예를 들어, 클릭 한 번으로 URL이 변경되지 않는 경우<Link>클릭을 전혀 방지하거나 렌더링하고 싶다.<span>대신<Link>.

제 머릿속에 떠오르는 유일한 해결책은activeClassName(또는activeStyle및 설정pointer-events: none;단, IE9 및 IE10에서 동작하는 솔루션을 사용하고 싶습니다.

CSS를 사용할 수 있습니다.pointer-events기여하다.이것은 대부분의 브라우저에서 작동합니다.예를 들어 JS 코드:

class Foo extends React.Component {
  render() {
    return (
      <Link to='/bar' className='disabled-link'>Bar</Link>
    );
  }
}

및 CSS:

.disabled-link {
  pointer-events: none;
}

링크:

첨부된 HTML 링크를 비활성화하는 방법 답변은 두 가지 방법을 모두 사용하는 것이 좋습니다.disabled그리고.pointer-events: none최대 브라우저 지원을 제공합니다.

a[disabled] {
    pointer-events: none;
}

소스 링크:링크를 디세블로 하는 방법

이것으로 충분합니다.

<Link to={isActive ? '/link-to-route' : '#'} />

왜 이런 행동을 원하냐고 묻진 않겠지만<Link />커스텀 링크 컴포넌트로 설정합니다.

<MyLink to="/foo/bar" linktext="Maybe a link maybe a span" route={this.props.route} />

class MyLink extends Component {
    render () {
        if(this.props.route === this.props.to){
            return <span>{this.props.linktext}</span>
        }
        return <Link to={this.props.to}>{this.props.linktext}</Link>
    }
}

(ES6, 하지만 대략적인 내용은 알고 계실 겁니다.)

같은 경로를 이미 클릭한 경우 클릭 이벤트를 비활성화할 수도 있습니다.다음은 리액트 라우터 v4와 연동되는 솔루션입니다.

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

class SafeLink extends Component {
    onClick(event){
        if(this.props.to === this.props.history.location.pathname){
            event.preventDefault();
        }

        // Ensure that if we passed another onClick method as props, it will be called too
        if(this.props.onClick){
            this.props.onClick();
        }
    }

    render() {
        const { children, onClick, ...other } = this.props;
        return <Link onClick={this.onClick.bind(this)} {...other}>{children}</Link>
    }
}

export default withRouter(SafeLink);

그 후 링크를 다음과 같이 사용할 수 있습니다.Link동작합니다).

<SafeLink className="some_class" to="/some_route">Link text</SafeLink>

무효화 기능을 갖춘 리액트 라우터 NavLink의 모든 장점.

import React from "react"; // v16.3.2
import { withRouter, NavLink } from "react-router-dom"; // v4.2.2

export const Link = withRouter(function Link(props) {
  const { children, history, to, staticContext, ...rest } = props;
  return <>
    {history.location.pathname === to ?
      <span>{children}</span>
      :
      <NavLink {...{to, ...rest}}>{children}</NavLink>
    }
  </>
});

리액트 라우터Routecomponent에는 현재 경로를 기반으로 콘텐츠를 렌더링하는 세 가지 방법이 있습니다.하는 동안에component일반적으로는 일치 중에만 컴포넌트를 표시하기 위해 사용됩니다.children컴포넌트는({match}) => {return <stuff/>}콜백: 루트가 일치하지 않는 경우에도 일치 시 캐시된 내용을 렌더링할 수 있습니다.

링크를 스팬으로 대체하고 NavLink 클래스가 생성되었을 때 클래스를 추가합니다.toroute는 활성화 되어 있습니다.

class NavLink extends Component {
  render() {
    var { className, activeClassName, to, exact, ...rest } = this.props;
    return(
      <Route
        path={to}
        exact={exact}
        children={({ match }) => {
          if (match) {
            return <span className={className + " " + activeClassName}>{this.props.children}</span>;
          } else {
            return <Link className={className} to={to} {...rest}/>;
          }
        }}
      />
    );
  }
}

그런 다음 다음과 같은 네비게이션 링크를 만듭니다.

<NavLink to="/dashboard" className="navlink" activeClassName="active">

Respect Router의 NavLink는 비슷한 기능을 하지만 사용자는 여전히 링크를 클릭하여 이력을 푸시할 수 있습니다.

const [isActive, setIsActive] = useState(true); 


<Link to={isActive ? '/link-to-route' :  null} />

이거 한 번 해봐, 나한테는 효과가 있었어.

다음과 같은 슬림한 커스텀 컴포넌트를 작성하면 스타일링과 css를 적용할 수 있습니다.또, 불투명도나 포인터 이벤트도 사용할 수 있습니다.없음...또는 소품에서 비활성화된 경우 "to"를 null로 설정할 수 있습니다.

type Props = { disabled?: boolean;} & LinkProps; 

const CustomLinkReactRouter = (props: Props) => {
    const { disabled, ...standardProps } = props;
    return <Link {...standardProps} onClick={e => disabled && e.preventDefault()}/> 
}
export default CustomLinkReactRouter;

nbeuchat의 답변과 컴포넌트를 기반으로 컴포넌트를 오버라이드하는 독자적인 개량 버전을 작성했습니다.react router's Link컴포넌트입니다.

저 것을 안 .toreact-router-dom does) link does) search query ★★★★★★★★★★★★★★★★★」hash pathname

import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Link as ReactLink } from 'react-router-dom';
import { withRouter } from "react-router";

const propTypes = {
  to: PropTypes.oneOfType([PropTypes.string, PropTypes.func, PropTypes.object]),
  location: PropTypes.object,
  children: PropTypes.node,
  onClick: PropTypes.func,
  disabled: PropTypes.bool,
  staticContext: PropTypes.object
};

class Link extends Component {
  handleClick = (event) => {
    if (this.props.disabled) {
      event.preventDefault();
    }

    if (typeof this.props.to === 'object') {
      let {
        pathname,
        search = '',
        hash = ''
      } = this.props.to;
      let { location } = this.props;

      // Prepend with ? to match props.location.search
      if (search[0] !== '?') {
        search = '?' + search;
      }

      if (
        pathname === location.pathname
        && search === location.search
        && hash === location.hash
      ) {
        event.preventDefault();
      }
    } else {
      let { to, location } = this.props;

      if (to === location.pathname + location.search + location.hash) {
        event.preventDefault();
      }
    }

    // Ensure that if we passed another onClick method as props, it will be called too
    if (this.props.onClick) {
      this.props.onClick(event);
    }
  };

  render() {
    let { onClick, children, staticContext, ...restProps } = this.props;
    return (
      <ReactLink
        onClick={ this.handleClick }
        { ...restProps }
      >
        { children }
      </ReactLink>
    );
  }
}

Link.propTypes = propTypes;

export default withRouter(Link);

또 다른 은 ' 정도'를 입니다.ConditionalWrapper.<Link>조건에 따라 태그를 지정합니다.

은 ★★★입니다.ConditionalWrapper이 컴포넌트는 https://blog.hackages.io/conditionally-wrap-an-element-in-react-a8b9a47fab2의 블로그를 기반으로 사용되었습니다.

const ConditionalWrapper = ({ condition, wrapper, children }) =>
    condition ? wrapper(children) : children;

export default ConditionalWrapper

사용 방법은 다음과 같습니다.

const SearchButton = () => {
    const {
        searchData,
    } = useContext(SearchContext)

    const isValid = () => searchData?.search.length > 2

    return (<ConditionalWrapper condition={isValid()}
                                wrapper={children => <Link href={buildUrl(searchData)}>{children}</Link>}>
            <a
                className={`ml-auto bg-${isValid()
                    ? 'primary'
                    : 'secondary'} text-white font-filosofia italic text-lg md:text-2xl px-4 md:px-8 pb-1.5`}>{t(
                    'search')}</a>
        </ConditionalWrapper>
    )
}

에서는 「」는 되지 .Link또한 코드 중복을 방지합니다.

설계에 맞는 경우 그 위에 div를 넣고 z 인덱스를 조작합니다.

언급URL : https://stackoverflow.com/questions/35963070/react-router-how-to-disable-a-link-if-its-active

반응형