reactjs - 组件的条件类型取决于带有样式组件的道具?
问题描述
我在 onPress 的组件中有一个道具,当 onPress 为真时,我想渲染 TouchableOpacity 或如果 onPress 为假则查看,这是我的代码:
const Card: FC<CardProps> = ({ title, subTitle, onPress }) => {
return (
<Container onPress={onPress}>
...
const Container = styled.View`
flex-direction: row;
padding-horizontal: 7px;
padding-vertical: 12px;
background-color: #fff;
shadow-opacity: 0.08;
shadow-radius: 25px;
elevation: 8;
shadow-color: rgb(0, 0, 0);
shadow-offset: 0px 1px;
border-radius: 8px;
margin-bottom: 10px;
`;
我要避免的是进行另一个常量声明,例如:
const TouchableContainer = styled.TouchableOpacity`
flex-direction: row;
padding-horizontal: 7px;
padding-vertical: 12px;
background-color: #fff;
shadow-opacity: 0.08;
shadow-radius: 25px;
elevation: 8;
shadow-color: rgb(0, 0, 0);
shadow-offset: 0px 1px;
border-radius: 8px;
margin-bottom: 10px;
`;
并做:
onPress? <ToucableContainer> : <Container>
因为它会觉得多余?我对高阶组件感到困惑,所以我想知道正确的方法是什么?谢谢
解决方案
为我在组件内声明一个样式化的组件感觉很奇怪,但这就是我所做的:
const Card: FC<CardProps> = ({ title, subTitle, onPress }) => {
const StyledContainer = styled(onPress ? TouchableOpacity : View)`
flex-direction: row;
padding-horizontal: 7px;
padding-vertical: 12px;
background-color: #fff;
shadow-opacity: 0.08;
shadow-radius: 25px;
elevation: 8;
shadow-color: rgb(0, 0, 0);
shadow-offset: 0px 1px;
border-radius: 8px;
margin-bottom: 10px;
`;
return (
<StyledContainer {...(onPress && { onPress })}>
无论如何对我有用,让我知道是否有更好的方法
推荐阅读
- active-directory - 使用 Javascript 将 objectGuid 转换为 UUID 字符串
- assembly - 如何在裸机上获取平面二进制代码地址?
- scala - 演员上的scala.MatchError
- c# - 客户详细信息页面未正确重定向。它没有在 ActionName 之后附加“Id”输入参数
- java - 异步任务减慢问题
- css - 相对于不是其直接父元素的元素,如何以 % 为单位定义容器的宽度?
- c# - 为什么有时在运行游戏时,游戏中的文字字幕是黑色的?
- android - 如何通过 android 下拉菜单/布局上的手势实现展开/折叠?
- c# - 使用 pax 设备在 c# 或 Vb.net 中集成 POS 链接支付
- r - 我想在我的代码中使用热图,但出现错误