React:如何避免动态返回组件时代码重复?已尝试dynamic方案
规避React组件重复props传递的几种实用方案
看你这段代码里,核心的重复点在于两个分支都要传递相同的apple和banana props,而且组件选择的条件逻辑也可以更简洁。除了你试过的dynamic方案,这里给你几个好用的替代思路:
方案1:组件映射表 + 展开运算符(最推荐,扩展性强)
把要切换的组件存进一个对象映射表,通过componentTitle直接匹配目标组件,再用展开运算符一次性传递所有共享props,彻底消除重复:
import React from 'react'; import {FirstCustomComponent} from './somewhere'; import {SecondCustomComponent} from './somewhere-else'; // 建立组件与名称的映射关系 const componentMap = { FirstCustomComponent, SecondCustomComponent }; const ThirdCustomComponent = ({componentTitle, ...sharedProps}) => { // 根据标题获取目标组件 const TargetComponent = componentMap[componentTitle]; // 处理不存在的组件名称,返回null或默认组件 if (!TargetComponent) return null; // 一次性传递所有共享props return <TargetComponent {...sharedProps} />; }; export default ThirdCustomComponent;
后续如果要新增更多可切换的组件,只需要在componentMap里加一行就行,维护成本极低。
方案2:提取共享props到变量(改动最小,适合简单场景)
如果只是不想重复写props传递,也可以把重复的props打包成一个对象,在两个分支里展开:
import React from 'react'; import {FirstCustomComponent} from './somewhere'; import {SecondCustomComponent} from './somewhere-else'; const ThirdCustomComponent = ({componentTitle, apple, banana}) => { // 把重复的props打包成一个对象 const sharedProps = {apple, banana}; return componentTitle === 'FirstCustomComponent' ? <FirstCustomComponent {...sharedProps} /> : <SecondCustomComponent {...sharedProps} />; }; export default ThirdCustomComponent;
这个方案几乎不需要改动原有逻辑,适合只有两个组件切换的简单场景,可读性拉满。
方案3:React.cloneElement(适合组件注入场景)
如果你的场景允许把组件直接作为prop传入(而不是通过字符串名称匹配),可以用cloneElement给传入的组件追加props:
import React from 'react'; import {FirstCustomComponent} from './somewhere'; import {SecondCustomComponent} from './somewhere-else'; const ThirdCustomComponent = ({targetComponent, apple, banana}) => { // 给传入的组件实例追加共享props return React.cloneElement(targetComponent, {apple, banana}); }; // 使用示例: // <ThirdCustomComponent targetComponent={<FirstCustomComponent />} apple="红苹果" banana="黄香蕉" />
这个方案适合更灵活的组件注入场景,不过需要调整组件的调用方式。
你可以根据自己的实际业务场景选最合适的方案~
内容的提问来源于stack exchange,提问作者TDB
相关产品推荐
相关产品推荐

