首页 > 解决方案 > 如何让平面列表只呈现一次?

问题描述

我试图只打印一次 ComponentTwo Flatlist ,但相反,我得到了结果image1但相反,我需要它看起来像这个图像 2。我附上了一个小吃链接,里面有代码。

将产生与图像Expo Snack Link中相同结果的代码

标签: javascripttypescriptreact-nativereact-native-flatlistflatlist

解决方案


工作示例:世博小吃

在此处输入图像描述

这是解决此问题的方法,首先将index值传递给ComponentOnefromApp.js

const App = () => {
 return (
      <SafeAreaView style={styles.container}>
        <FlatList
            data={DATA}
            renderItem={({item, index}) => <ComponentOne name={item.title} index={index}/>}
            keyExtractor={(item) => item.id}
        />
      </SafeAreaView>
  );
};

现在使用该道具值ComponentTwo有条件地渲染,ComponentOne如下所示:

//...const 

ComponentOne = (props: ComponentOneProps) => {
  return (
    <View style={{ margin: 15, backgroundColor: 'yellow' }}>
      <FlatList
        data={recent}
        renderItem={({ item }) => {
          console.log("hello")
          // @ts-ignore
          return props.index == 0?<ComponentTwo name={item.name} />:null;
        }}
        keyExtractor={(item) => item.idd}
      />
//...

推荐阅读