Los enlaces de enrutador React se pueden usar en componentes de función para recuperar la ruta actual.
Sin embargo, no puedo encontrar ninguna referencia para el componente de clase .
Tengo un menú de navegación y quiero realizar un seguimiento de la ruta actual para resaltarla en la parte delantera cambiando las clases de css según el estado actual.
Extracto de navegación:
import React, { Component, Fragment } from 'react'; import { Link } from 'react-router-dom'; ... export default class Nav extends Component { ... render = (): JSX.Element => { return ( <> {/* Current: "border-green-500 text-gray-900" */} {/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */} <Link to="/" className="border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700 inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium" > Home </Link> </> ); } }¿Hay algún método para lograr este objetivo en un componente de clase de reacción?
¡Gracias de antemano!
¡Gracias a @genius fox dev, esta solución funcionó para mí!
{/* Current: "border-green-500 text-gray-900" */} {/* Default: "border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700" */} <NavLink // from 'react-router-dom' to="/" className={ ( {isActive} ) => ( isActive ? 'border-green-500 text-gray-900' : 'border-transparent text-gray-500 hover:border-gray-300 hover:text-gray-700' ).concat( ' inline-flex items-center px-1 pt-1 border-b-2 text-sm font-medium' ) } > Home </NavLink>Puede utilizar NavLink compatible con react-router-rom v6.0.
Primero, cambie el enlace a navlink y luego muestre cuidadosamente el código debajo.
<NavLink style={({ isActive }) => { return { display: "block", margin: "1rem 0", color: isActive ? "red" : "" }; }} to={`/invoices/${invoice.number}`} key={invoice.number} > {invoice.name} </NavLink>por favor, consulte la URL. https://reactrouter.com/docs/en/v6/getting-started/tutorial#active-links