React-Router V5 尝鲜🍉🍉

1,366 阅读1分钟

新特性

  • 完全兼容老版本v4
  • 支持 React 16 , 兼容 React >= 15
  • 消除在 React.StrictMode 严格模式中的警告
  • 使用 create-react-context 实现 context API

新功能

  • Route 组件 path 可以为数组
    • before
      <Switch>
        <Route path="/users/:id" component={User} />
        <Route path="/profile/:id" component={User} />
      </Switch>
      
    • after
      <Route path={["/users/:id", "/profile/:id"]} component={User} />
      
  • 支持 React.createRef in <Link innerRef>
    • 举个栗子
      // 通过以下方式可以获取到 Link 组件对应的 DOM 元素
      this.createRef = React.createRef();
      
      <Link to="/home" innerRef={this.createRef}>home</Link>
      
  • 支持 React.forwardRef in <Route component>
    • 举个栗子
      <Route path="/home" component={Home}/>
      
      // Home 组件
      export default React.forwardRef((props, ref) => {
        // 纯函数组件也能获取到 ref (当前 Home 组件对应的 DOM 元素)
        console.log(props, ref);
        return <h2>Home</h2>
      })
      

以上功能是 v4 没有的功能,而在 v5 新增的。
什么?还想知道更多内幕消息?关注这个博客吧 --> 博客传送门