React实现Step组件的示例代码
简介
本文将会实现步骤条组件功能。步骤条在以下几个方面改进。
1、将url与Step组件绑定,做到浏览器刷新,不会重定向到Step 1
2、通过LocalStorage 存储之前的Step,做到不丢失数据。
实现
Step.jsx (组件)
import {useEffect, useState} from "react";
export const Step = ({name, data})=>{
const submit = (event)=>{
event.preventDefault();
const local = localStorage.getItem(name);
console.log(JSON.parse(local))
}
const [current, setCurrent] = useState(0);
useEffect(()=>{
let paths = window.location.pathname.split('/');
setCurrent(parseInt(paths[paths.length - 1]));
}, [])
return (
<form className={'Step'} onSubmit={submit}>
<div className={'Step-Header'}>
<div>
{
data.map((item, idx) =>{
return <a key={idx} href= {`/step/${idx}`} style={{paddingRight:30}}>{item.name + ((idx === current) ? '√':'')}</a>;
})
}
</div>
</div>
<div className={'Step-Content'}>
{data[current].content}
</div>
<div className={'Step-Footer'}>
{current > 0 && <button onClick={()=>setCurrent(current-1)}>pre</button>}
{current + 1 < data.length && <button onClick={()=> setCurrent(current+1)}>next</button>}
{current === data.length - 1 && <button type="submit">提交</button>}
</div>
</form>
);
}
1. Step会获取浏览器url中的步骤数,并设置Step-Content。
2.表单在最后一个步骤会有提交按钮,会从local storage中获取表单参数
3.step header 是导航栏, step content是具体的内容,step footer为步骤条操作按钮。
app.jsx (使用)
unction App() {
const stepName = 'Demo';
const Step1 = ()=>{
const local = localStorage.getItem(stepName);
const [username, setUsername] = useState(local ? local.username:'');
const change = (event)=>{
setUsername(event.target.value);
localStorage.setItem(stepName, JSON.stringify({
username: event.target.value
}));
}
return <>
<label htmlFor='username'>用戶名:</label><input type={'text'} value={username} onChange={change}/>
</>;
}
const steps = [
{
name: "步驟1",
content: <Step1/>
},
{
name: "步驟2",
content: (<span>2号</span>)
}
]
return <Step data={steps} name={stepName} />
}
export default App;
1.Step1组件需要将表单数据与localStorage绑定
到此这篇关于React实现Step组件的示例代码的文章就介绍到这了,更多相关React Step组件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
React 中useLayoutEffect 和 useEffect 区别和使用
本文主要介绍了React 中useLayoutEffect 和 useEffect 区别和使用场景,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2026-05-05
React Native开发封装Toast与加载Loading组件示例
这篇文章主要介绍了React Native开发封装Toast与加载Loading组件,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-09-09
React+Ant Design前端实现读取与导出Excel文件
在实际业务场景中,我们经常需要处理 Excel 文件的导入导出,本文将以 React + Ant Design 项目为例,演示如何通过 xlsx 库实现以下功能,希望对大家有所帮助2025-08-08
React-router中结合webpack实现按需加载实例
本篇文章主要介绍了React-router中结合webpack实现按需加载实例,非常具有实用价值,需要的朋友可以参考下2017-05-05
React onBlur回调中使用document.activeElement返回body完美解决方案
这篇文章主要介绍了React onBlur回调中使用document.activeElement返回body完美解决方案,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-04-04


最新评论