使用三元运算符来响应本机自定义组件

问题描述 投票:0回答:1

我的代码可以完美工作,但是我想使用三元运算符来编写它,但我做不到。我可以帮忙吗?我尝试了一种在三元运算符内部具有2个返回值的形式,但它似乎不起作用。谢谢。

import React from 'react';
import Card from './Card';

import { ScrollView, View, Text } from 'react-native';

const CardList = ({ list, onRemoveButton }) => {

  if (list.length === 0) {
    return(
      <View>
        <Text 
          style={{
            fontSize: 20,
            padding: 20,
            lineHeight: 30,
            textAlign: "center"
          }}
        >
        It seems like u have nothing to Do, Relax and Have fun</Text>
      </View>
    );
  } else {
    return(
      <ScrollView style={{paddingTop: 8}}>
      {
        list.map((text, i) => {
          return (
            <Card onRemoveButton={onRemoveButton} key={i} id={i} text={text} />
          );
        })
      }
    </ScrollView>
    );
  }
}

export default CardList

更新:已解决!我必须在三元运算符之前使用return,但我没有注意到。

javascript react-native ternary-operator
1个回答
0
投票
import React from 'react';
import Card from './Card';
import { ScrollView, View, Text } from 'react-native';

const CardList = ({ list, onRemoveButton }) => {
  return list.length ? ( // length > 0 is truthy
      <ScrollView style={{paddingTop: 8}}>
        {
          list.map((text, i) => {
            return (
              <Card onRemoveButton={onRemoveButton} key={i} id={i} text={text} />
            );
          })
        }
      </ScrollView>
    ) : (
      <View>
        <Text 
          style={{
            fontSize: 20,
            padding: 20,
            lineHeight: 30,
            textAlign: "center"
          }}
        >
          It seems like u have nothing to Do, Relax and Have fun</Text>
      </View>
    );
  }
}

export default CardList
© www.soinside.com 2019 - 2024. All rights reserved.