如何在 flatlist 中进行条件渲染

时间:2021-05-04 22:33:55

标签: json typescript react-native return react-native-flatlist

我从一个记录国家名称和人口的 API 中获取。我在搜索平面列表中有国家名称。我的目标是根据人口在平面列表上的国家名称旁边显示一个小圆圈。如果人口在100M以上,则圆圈为红色,如果人口在10M以上且小于50M,则圆圈为橙色,如果小于10M,则圆圈为绿色。条件渲染是执行此操作的正确方法吗?或者我可以用不同的方式来做吗?

我当前的代码如下:

const [filteredData, setFilteredData] = useState<any>();
const [masterData, setMasterData] = useState([]);
const [filteredPopulationData, setFilteredPopulationData] = useState<any>();
const [masterPopulationData, setMasterPopulationData] = useState([]);

useEffect(() => {
    fetchData();
    return () => {};
  }, []);

const fetchData = () => {
    const apiURL =
      "https://raw.githubusercontent.com/samayo/country-json/master/src/country-by-population.json";
    fetch(apiURL)
      .then((response) => response.json())
      .then((responseJson) => {
        setFilteredStateData(responseJson);
        setMasterStateData(responseJson);
      })
      .catch((error) => {
        console.error(error);
      });
  };

const SearchFilter = (text) => {
    if (text) {
      const newData = filteredData.filter((item) => {
        const itemData = item.country;

        const textData = text.toUpperCase();
        return itemData.indexOf(textData) > -1;
      });

      setFilteredData(newData);
      setSearch(text);
    } else {
      setFilteredData(masterData);
      setSearch(text);
    }
    if (text) {
      const newPopulationData = filteredPopulationData.filter((item) => {
        const itemPopulationData = item.population;

        const textPopulationData = text.toUpperCase();
        return itemPopulationData.indexOf(textPopulationData) > -1;
      });

      setFilteredPopulationData(newPopulationData);
      setSearch(text);
    } else {
      setFilteredPopulationData(masterPopulationData);
      setSearch(text);
    }

const renderExtraItem = ({ item }) => {
    if ((item.population < 10000000)) {
      return (
        <View
          style={{
            width: 10,
            height: 10,
            borderRadius: 20,
            backgroundColor: "green",
          }}
        />
      );
    } if ((item.population >= 10000000 && item.population < 50000000 )) {
      return (
        <View
          style={{
            width: 10,
            height: 10,
            borderRadius: 20,
            backgroundColor: "orange",
          }}
        />
      );
    } if ((item.population >= 100000000)) {
      return (
        <View
          style={{
            width: 10,
            height: 10,
            borderRadius: 20,
            backgroundColor: "red",
          }}
        />
      );
    }
  };

const ItemView = ({ item }) => {
    return (
      <RectButton
        onPress={() => navigate("LocationDataScreen", { name: item.country })}
      >
        <Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
          {item.id}
          {item.country.toUpperCase()}
        </Text>
        {renderExtraItem(item)}
      </RectButton>
    );
  };
const ItemSeparatorView = () => {
    return (
      <View
        style={{
          height: 1.5,
          width: "90%",
          marginLeft: 35,
          backgroundColor: "#f3f2f8",
        }}
      />
    );
  };

return (
<FlatList
        data={filteredData}
        keyExtractor={(item, index) => index.toString()}
        ItemSeparatorComponent={ItemSeparatorView}
        renderItem={ItemView}
        style={styles.listcontainer}
      />
)

2 个答案:

答案 0 :(得分:1)

您可以简单地使用一个函数来根据上述条件显示自定义元素

 const renderExtraItem = (item) => {
    if (item.population > 100000000) {
      //render some custom view
      return (
        <View />
      )
    }

    if (item.population > 10000000 && item.population < 50000000) {
      // render something else
      return (<View />)
    }

    // render a default 
    return (<View />)
  }

  const ItemView = ({ item }) => {
    return (
      <RectButton
        onPress={() => navigate("LocationDataScreen", { name: item.country })}
      >
        <Text style={[styles.itemStyle, { textTransform: "capitalize" }]}>
          {item.id}
          {item.country.toUpperCase()}
        </Text>
        {renderExtraItem(item)}
      </RectButton>
    );
  };

答案 1 :(得分:0)

是的,这是正确的方法。
注意 population >= xxpopulation > xx

你的代码可能是这样的:

const YourItemComponent = ({population}) => {

   //function that return color based on population
   const getCircleColor = (population) => {
      if(population >= 100000000) return "red";   
      if(population >= 10000000 && population < 50000000) return "orange"; 
      return "green";
   };

   return(
     <View>
        ...
        <Circle style={{backgroundColor : getCircleColor(population)}}>
      
        </Circle>
       ...
    </View>
   );

}