【问题标题】:Create a Progress Bar with React Router使用 React Router 创建进度条
【发布时间】:2019-03-27 22:16:54
【问题描述】:

我正在使用 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,但没有成功。 有没有更优雅的解决方案?谢谢! :)

【问题讨论】:

  • 在你进一步移动之前,假设你已经按照你想要的方式工作了,如果用户直接跳转到 /form/2 会发生什么?看起来进度应该由一个完全独立的、有状态的组件来跟踪,该组件跟踪每个问题是否已得到回答。

标签: reactjs react-redux react-router


【解决方案1】:

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

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>
  )
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-18
    • 2020-08-12
    • 2019-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多