React Native TypeScript如何动态修改数组渲染的styled文本组件属性
实现方案
方案1:直接修改原数字样式(推荐)
这种方式不需要额外叠加元素,直接通过styled-components的透传属性控制已填充状态的样式:
- 先给
OrderText组件添加isFilled属性来控制样式切换,注意修正原有代码末尾多余的右大括号语法错误:
const OrderText = styled(Text).attrs(() => ({ type: TextTypes.H4, }))<{ isFilled: boolean }>` border-color: ${({theme, isFilled}) => isFilled ? theme.colors.primary : theme.colors.lightGreyBackground}; background: ${({theme, isFilled}) => isFilled ? theme.colors.primary : theme.colors.background}; color: ${({theme, isFilled}) => isFilled ? theme.colors.white : theme.colors.text}; text-align: center; padding-top: 5px; width: 35px; height: 35px; border-radius: 999px; border-width: 3px; `;
- 渲染数字的时候把当前订单号和
filled的对比结果传给isFilled属性,同时给map循环添加唯一key避免React警告:
const displayOrders = () => orderCount.map((ORDERS, index) => ( <OrderTextContainer key={index}> <OrderText isFilled={ORDERS.orderNumber <= filled}> {ORDERS.orderNumber} </OrderText> </OrderTextContainer> ));
- 在storybook测试的时候记得传入
filled参数:
storiesOf('Loyalty Status', module).add('Default', () => ( <LoyaltyStatus statusTier="Gold" points={10} filled={3} // 填入测试值,比如3代表1、2、3都显示为已填充状态 orderCount={dummy.map((order) => ({ orderNumber: order.id, }))} /> ));
方案2:叠加盖章层(你提到的自行实现方案)
如果需要实现带特殊标记的盖章效果,需要补充对应样式配置:
- 给父容器
OrderTextContainer添加相对定位,作为叠加层的定位基准:
const OrderTextContainer = styled.View` position: relative; flex-direction: column; flex-grow: 0; flex-shrink: 1; padding: 10px; background: ${({theme}) => theme.colors.background}; `;
- 定义
FilledOrderText的样式,设为绝对定位覆盖在原数字上方:
const FilledOrderText = styled(Text).attrs(() => ({ type: TextTypes.H4, }))` position: absolute; top: 10px; left: 10px; width: 35px; height: 35px; border-radius: 999px; background: ${({theme}) => `${theme.colors.primary}80`}; // 半透明效果模拟盖章 color: #fff; font-size: 10px; text-align: center; line-height: 35px; `;
- 渲染逻辑和你写的一致即可:
const displayOrders = () => orderCount.map((ORDERS, index) => ( <OrderTextContainer key={index}> <OrderText>{ORDERS.orderNumber}</OrderText> {ORDERS.orderNumber <= filled && ( <FilledOrderText>STAMPED</FilledOrderText> )} </OrderTextContainer> ));
内容的提问来源于stack exchange,提问作者Ibrahim Noor Mohammed
相关产品推荐
相关产品推荐

