react-router-dom V6 在类组件和js中使用


不说什么,简简单单的说就是发现怎么在类组件中和js中使用v6。

类组件中使用:

//  utils.js
import { useNavigate } from "react-router-dom";
export const withNavigation = (Component) => {
  return (props) => <Component {...props} navigate={useNavigate()} />;
};
// Three.js

import { withNavigation } from "./utils";
import React, { Component } from "react";
class Three extends Component {
  handleClick = () => {
    this.props.navigate("/two");
  }
  render() {
    return (
      <div>
        我是组件Three<button onClick={ this.handleClick }>go Two</button>
      </div>
    );
  }
}


export default withNavigation(Three);

简单的说就是可以使用withNavigation这个高级组件包裹类组件,然后在类组件中 this.props.navigate()使用,甚至你还可以在其中继续添加 useParams useLocation,不过听说新版本已经有对付这种方法的措施了,看来官方是真的不想我们用类组件了。

在非组件中使用

// getNavigation.js

let navigation = { nav: null };

export function setNavigation(nav) {
  navigation.nav = nav;
}
export default navigation; // 注册
// app.js
import { setNavigation } from "./getNavigation";
const App = () => {
  setNavigation(useNavigate())
  return (
    <div>
     ...
    </div>
  );
};
import navigate from "./getNavigation";
const Four = () => {
  const handleClick = () => {
    navigate.nav("/two");
  }
  return (
    <div>
      我是组件four
      <button onClick={() => handleClick()}>four</button>
    </div>
  );
}

简单的说就是在react 初始化前注册一个属性,然后将 useNavigate 赋值给这个属性,要用时从这个属性拿就好了。

当然,我的app已经在index.js中被BrowserRouter包裹了,也就是说不要在 BrowserRouter之外使用useNavigate!严格来说你在index中注册后就不应该有 useNavigate() may be used only in the context of a <Router> component. 这个报错。

目前官方还是没有给个在类组件和js中使用 v6 部分新特性的方法,如果看见有更好的方法或官方亲自说明,到时必会水上一篇。


文章作者: tttcpw
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 tttcpw !
  目录