如何精简含ReactDOM渲染的重复选项卡切换逻辑代码?
优化思路
原有代码的切换逻辑高度重复,核心差异仅为「待渲染组件」「对应容器节点」「触发按钮」三个变量,你提到的对象封装逻辑完全可行,通过配置表抽离公共逻辑、复用重复代码即可完成精简:
优化后的事件绑定代码
// 补全原代码缺失的acccont变量定义 const acccont = document.querySelector("#account_content"); const seccont = document.querySelector("#security_content"); const subcont = document.querySelector("#sub_content"); const accbtn = document.querySelector(".account"); const secbtn = document.querySelector(".security"); const subbtn = document.querySelector(".subscription"); // 统一管理所有tab的关联配置 const tabConfig = [ { component: <Account />, container: acccont, btn: accbtn }, { component: <Security />, container: seccont, btn: secbtn }, { component: <Subscription />, container: subcont, btn: subbtn } ]; // 公共切换逻辑,仅需维护一份 const switchTab = (activeTab) => { tabConfig.forEach(tab => { if (tab !== activeTab) { ReactDOM.unmountComponentAtNode(tab.container); tab.container.classList.add('hidden'); tab.btn.classList.remove('selected'); } }) ReactDOM.render(activeTab.component, activeTab.container); activeTab.container.classList.remove('hidden'); activeTab.btn.classList.add('selected'); } // 批量绑定事件 accbtn.onclick = () => switchTab(tabConfig[0]); secbtn.onclick = () => switchTab(tabConfig[1]); subbtn.onclick = () => switchTab(tabConfig[2]);
优化后的React业务代码
三个组件存在大量重复的表单项结构、跳转逻辑,可以进一步抽离公共组件和公共方法精简:
// 抽离公共表单项组件,复用重复结构 const FormItem = ({ label, type, id, name, autoComplete = 'off' }) => ( <li> <span>{label}</span> <input type={type} autoComplete={autoComplete} id={id} name={name} /> </li> ) // 抽离公共跳转逻辑,统一维护跳转地址 const goHome = () => window.open("/pixels/home/", "_self"); class Account extends React.Component { render() { return ( <div> <ul className="options"> <FormItem label="Login" type="text" id="login" name="login" /> <FormItem label="Email" type="text" id="email" name="email" /> <FormItem label="Nickname" type="text" id="nick" name="nick" /> </ul> <button id="apply_acc" onClick={goHome}>Save</button> </div> ); } } class Security extends React.Component { render() { return ( <div> <ul className="options"> <FormItem label="Old password" type="password" id="old_pwd" name="oldpwd" /> <FormItem label="New password" type="password" id="new_pwd" name="newpwd" autoComplete="new-password" /> <FormItem label="Repeat password" type="password" id="newpwd_repeat" name="newpwdrep" autoComplete="new-password" /> </ul> <button id="apply_sec" onClick={goHome}>Save</button> </div> ); } } class Subscription extends React.Component { render() { return ( <div> <button>TODO</button> </div> ); } }
优化收益
- 后续新增tab仅需在
tabConfig中新增配置即可,无需重复编写切换逻辑 - 公共逻辑统一维护,修改规则仅需调整一处,避免多份代码同步修改遗漏
- 修复了原代码中
acccont变量未定义的问题
内容的提问来源于stack exchange,提问作者MaxPayne420
相关产品推荐
相关产品推荐

