React Native中如何用Styled Components按onPress属性条件渲染容器
实现方案
Styled Components 提供了as prop 专门用于动态切换底层渲染的组件,是实现这个需求的最优解,性能更高也更易维护:
完整可运行代码
import * as React from 'react'; import { View, TouchableOpacity, TextStyle } from 'react-native'; import styled from 'styled-components/native'; import { Icon } from './Chevron'; export interface RowData { onPress?: () => void; showDisclosureIndicator: boolean; } // 先定义公共样式,底层默认用View即可 const StyledContentContainer = styled.View<{ // 加类型兼容as和onPress prop,避免TS报错 as?: React.ElementType; onPress?: () => void; }>` flex: 1; flex-direction: row; padding-left: 15px; align-items: center; background-color: white; `; // 你原来的Container样式自行保留,这里补个默认实现避免报错 const Container = styled.View` height: 50px; width: 100%; border-bottom-width: 1px; border-bottom-color: #eee; `; export const Row = ({ onPress, showDisclosureIndicator }: RowData) => { return ( <Container> {/* 动态通过as切换底层组件 */} <StyledContentContainer as={onPress ? TouchableOpacity : View} onPress={onPress} > {showDisclosureIndicator ? <Icon /> : <View />} </StyledContentContainer> </Container> ); };
可选方案(不推荐)
如果不想用as prop,也可以在组件内部动态创建Styled组件,但该方案会在onPress变化时重新生成组件,有额外性能开销:
export const Row = ({ onPress, showDisclosureIndicator }: RowData) => { // 动态生成带样式的容器 const ContentContainer = styled(onPress ? TouchableOpacity : View)` flex: 1; flex-direction: row; padding-left: 15px; align-items: center; background-color: white; `; return ( <Container> <ContentContainer onPress={onPress}> {showDisclosureIndicator ? <Icon /> : <View />} </ContentContainer> </Container> ); };
内容的提问来源于stack exchange,提问作者user12494839
相关产品推荐
相关产品推荐

