React中如何根据条件动态切换外层标签且不重复编写内部代码
实现方案
核心思路:JSX 支持将组件赋值给变量动态渲染,完全不需要重复编写内部嵌套内容。
方案1:单文件内最简实现(推荐)
import { Link } from 'react-router-dom'; import { Fragment } from 'react'; const route = "/home"; // 你的route变量,可能为空字符串 // 1. 动态决定外层容器 const Wrapper = route ? Link : Fragment; return ( // 2. 仅当容器为Link时传入to属性,避免Fragment收到无效属性告警 <Wrapper {...(route ? { to: route } : {})}> {/* 这里直接放所有内部内容,不需要重复编写 */} <ComponentA/> <ComponentB/> <ComponentC styles={mystyles}/> {var && <ComponentD/>} <ComponentE/> <ComponentF/> </Wrapper> );
方案2:通用封装(多场景复用)
如果项目中多次出现类似的条件包裹需求,可以封装为通用组件:
// 封装通用条件包裹组件 const ConditionalWrapper = ({ condition, wrapper, children }) => { return condition ? wrapper(children) : <>{children}</>; }; // 业务代码中直接调用 const route = "/home"; return ( <ConditionalWrapper condition={!!route} wrapper={(children) => <Link to={route}>{children}</Link>} > {/* 所有内部内容 */} <ComponentA/> <ComponentB/> <ComponentC styles={mystyles}/> {var && <ComponentD/>} <ComponentE/> <ComponentF/> </ConditionalWrapper> );
原写法错误原因
你之前尝试的半标签写法不符合JSX语法规则:JSX是语法糖,最终会编译为React.createElement调用,不支持半闭合的标签写法,也不能像字符串拼接一样只写开始标签不写结束标签。
内容的提问来源于stack exchange,提问作者yavgz
相关产品推荐
相关产品推荐

