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

如何使用styled-components为React Native不同组件复用相同样式

React Native 复用 Styled Components 重复样式的方案

针对你现在两个组件样式完全重复、仅底层原生组件不同的情况,以下是两种简洁可行的复用方案:

方案一:提取共享样式模板字符串

直接把重复的样式代码抽成单独的模板字符串,再分别应用到不同的 styled 组件上:

// 提取共享样式
const sharedCardStyles = `
  flex: 1;
  background-color: ${(props: any) => (props.expired ? '#ebebeb' : '#ffffff')};
  flex-direction: row;
  display: flex;
  padding-horizontal: 20px;
  padding-vertical: 12px;
  border-radius: 20px;
  margin: 3px 15px 3px 15px;
  shadow-color: #000;
  shadow-opacity: 0.23;
  shadow-radius: 2.62px;
  shadow-offset: 0px 3px;
  elevation: 4;
`;

// 基于不同原生组件创建复用样式的组件
const TouchableContainer = styled.TouchableOpacity`${sharedCardStyles}`;
const CardView = styled.View`${sharedCardStyles}`;

方案二:使用 css 辅助函数(更推荐)

借助 styled-components 提供的 css 工具函数,可以更优雅地管理带 props 的可复用样式,同时支持类型定义:

import styled, { css } from 'styled-components/native';

// 定义组件 props 类型(可选,提升类型安全)
type CardProps = {
  expired?: boolean;
};

// 用 css 函数提取共享样式
const sharedCardStyles = css<CardProps>`
  flex: 1;
  background-color: ${(props) => (props.expired ? '#ebebeb' : '#ffffff')};
  flex-direction: row;
  display: flex;
  padding-horizontal: 20px;
  padding-vertical: 12px;
  border-radius: 20px;
  margin: 3px 15px 3px 15px;
  shadow-color: #000;
  shadow-opacity: 0.23;
  shadow-radius: 2.62px;
  shadow-offset: 0px 3px;
  elevation: 4;
`;

// 创建组件时引入共享样式
const TouchableContainer = styled.TouchableOpacity`
  ${sharedCardStyles}
`;

const CardView = styled.View`
  ${sharedCardStyles}
`;

这两种方案都能彻底消除代码重复,后续修改样式只需维护一处即可,组件的 props 也能正常传递给样式中的逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:53:17