【问题标题】:conditional type of component depending on props with styled components?组件的条件类型取决于带有样式组件的道具?
【发布时间】:2021-01-15 10:37:44
【问题描述】:

我在一个组件中有一个道具,它是 onPress,当 onPress 为 true 时,我想渲染 TouchableOpacity 或如果 onPress 为 false 时查看,这是我的代码:

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>

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

【问题讨论】:

标签: reactjs react-native styled-components


【解决方案1】:

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

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

无论如何都适合我,如果有更好的方法,请告诉我

【讨论】:

    猜你喜欢
    • 2018-10-16
    • 2018-10-09
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2021-10-27
    • 2021-05-09
    • 2019-12-29
    • 1970-01-01
    相关资源
    最近更新 更多