You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在React中复用使用不同标签的组件

复用两个相似组件的优雅方案

你可以通过动态绑定标签类型的方式彻底消除代码重复——核心就是根据isPDF参数,把需要替换的div/p和View/Text做映射,然后组件里只写一套渲染逻辑。

基础实现代码

interface ClaimedLabelProps {
  isPDF: boolean;
}

const ClaimedLabel = ({ isPDF }: ClaimedLabelProps): React.ReactElement => {
  // 按需选择对应标签
  const Root = isPDF ? 'View' : 'div';
  const Text = isPDF ? 'Text' : 'p';
  const Container = isPDF ? 'View' : 'div';

  return (
    <Root tw="">
      <Text tw="">Some Text here</Text>
      <Container tw="">
        <Icon src="./icon.png" />
      </Container>
    </Root>
  );
};

进阶优化:用映射对象管理标签

如果以后要加更多不同的标签,用映射对象管理会更清晰,也方便扩展:

interface ClaimedLabelProps {
  isPDF: boolean;
}

const ClaimedLabel = ({ isPDF }: ClaimedLabelProps): React.ReactElement => {
  const tags = {
    root: isPDF ? 'View' : 'div',
    text: isPDF ? 'Text' : 'p',
    container: isPDF ? 'View' : 'div',
  };

  const { root: Root, text: Text, container: Container } = tags;

  return (
    <Root tw="">
      <Text tw="">Some Text here</Text>
      <Container tw="">
        <Icon src="./icon.png" />
      </Container>
    </Root>
  );
};

为啥这方案更好?

  • 只需要维护一套内容结构,改文本、样式或者Icon属性时,不用两边重复修改
  • 标签映射逻辑一目了然,后续要加其他平台的标签(比如小程序的view/text)也很方便
  • 完全避免了三元表达式里重复写大段JSX的冗余问题

如果是跨平台场景(比如Web+React Native),注意确保View/Text这些标签在对应环境中能正常导入使用就行。

内容的提问来源于stack exchange,提问作者Uladz Kha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:15:34