首页 > 解决方案 > 使用 React Router 创建进度条

问题描述

我正在使用 react-router 为 9 页表单设置进度条。我的目标是使用 Switch 和 Route 组件为用户浏览的每个页面更新 1/9 的宽度。

我目前在访问 Switch 的子节点数量和自动化进度条时遇到问题。当然,解决方法可能是每次安装组件时硬编码 1/9,但这并不理想。

// Routes I'm want to get 'progress' from
let routes = (
      <Switch>
        <Route path="/form/" exact component={Question0} />
        <Route path="/form/1" component={Question1} />
        <Route path="/form/2" component={Question2} />
        <Route path="/form/tip1" component={Tip1} />
        <Route path="/form/3" component={Question3} />
        <Route path="/form/tip2" component={Tip2} />
        <Route path="/form/4" component={Question4} />
        <Route path="/form/tip3" component={Tip3} />
        <Route path="/form/5" component={Question5} />
      </Switch>
    );

我也尝试过使用 React.Children,但没有成功。有没有更优雅的解决方案?谢谢!:)

标签: reactjsreact-reduxreact-router

解决方案


您可以编写自定义开关并使用它来代替默认开关:

const SwitchProgress = withRouter(props => {
  const progress = props.children.findIndex(
    route => matchPath(props.location.pathname, route.props)
  ) + 1;
  return (
    <React.Fragment>
      <div>Progress: {progress} / {props.children.length}</div>
      <Switch>
        {props.children}
      </Switch>
    </React.Fragment>
  )
});

推荐阅读