【问题标题】:How to do conditional rendering in flatlist如何在 flatlist 中进行条件渲染
【发布时间】:2021-07-27 06:54:06
【问题描述】:

我从一个记录国家名称和人口的 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}
      />
)

【问题讨论】:

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


    【解决方案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>
        );
      };
    

    【讨论】:

    • 当我这样做时,所有的小圆圈都是相同的颜色,即使我在每个 if 语句中为每个视图组件设置了不同的颜色。
    • @dannym 是string 还是number?在条件语句中尝试parseInt(item.population,10) 以消除人口为string 的情况。
    • 人口是number,你可以检查json文件来确定。我还更新了我的代码以显示您的答案。让我知道它是否正确。
    【解决方案2】:

    是的,这是正确的方法。
    注意population &gt;= xxpopulation &gt; 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>
       );
    
    }
    
    

    【讨论】:

    • 谢谢你。但是,YourItemComponent 是什么,我应该把它放在我的代码中的什么位置?当我尝试这样做时,所有的圆圈都是红色的。我已经更新了我的代码以包含人口数据。
    • 对你来说意味着ItemView 。我写YourItemComponent只是为了解释。
    猜你喜欢
    • 1970-01-01
    • 2021-06-13
    • 2022-07-05
    • 1970-01-01
    • 2020-09-20
    • 1970-01-01
    • 1970-01-01
    • 2021-07-18
    • 2019-04-04
    相关资源
    最近更新 更多