首页 > 解决方案 > 组件的条件类型取决于带有样式组件的道具?

问题描述

我在 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>

因为它会觉得多余?我对高阶组件感到困惑,所以我想知道正确的方法是什么?谢谢

标签: reactjsreact-nativestyled-components

解决方案


为我在组件内声明一个样式化的组件感觉很奇怪,但这就是我所做的:

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 })}>

无论如何对我有用,让我知道是否有更好的方法


推荐阅读