reactjs - 使用 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,但没有成功。有没有更优雅的解决方案?谢谢!:)
解决方案
您可以编写自定义开关并使用它来代替默认开关:
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>
)
});
推荐阅读
- javascript - Javascript 不适用于 ie 浏览器和 ff
- metal - 想要放弃 MTKView.currentRenderPassDescriptor
- java - 阿帕奇卡夫卡:寻找和分配。从头开始可靠读取
- c# - 使用SharpAVI录屏,为什么我提高FPS后播放的.avi文件好像加速了?
- javascript - 排序 ng-table(空值和自定义排序)
- javascript - FlowJS - 无法识别可选字段何时有值
- unix - 在字符串中查找负数
- python - 什么相当于 Python 3.x 中的“bwlabeln(具有 18 和 26 连接的邻域)”?
- python - 从另一个 Python 脚本导入函数时,如何确保导入的模块正常工作?
- python - 如何操作 Google Ads API 的 Enum 类的对象 - python