如何在React Native中以字母顺序设置标题?

huangapple go评论61阅读模式
英文:

How to set header in Alphabetic way in react native?

问题

# **输出**

[![在这里输入图片描述](https://i.stack.imgur.com/0PkVA.jpg)](https://i.stack.imgur.com/0PkVA.jpg)

# **代码**

```jsx
import React from 'react';
import {
  Text,
  View,
  FlatList,
  ScrollView,
  SafeAreaView
} from 'react-native';

import { nameData } from './dummydata';

const windowSize = FlatList.length > 50 ? FlatList.length / 4 : 21;

const Main = () => {
  return (
    <View style={{}}>
      <SafeAreaView style={{}}>
        <ScrollView style={{}}>
          <FlatList
            disableVirtualization={true}
            //data={nameData.sort((a, b) => a.name.localeCompare(b.name))}
            data={nameData.sort(function (a, b) {
              return (a.name < b.name) ? -1 : (a.name > b.name) ? 1 : 0;
            })}
            renderItem={({ item }) => (
              <Text style={{ fontSize: 20,marginLeft:10,padding:5 }}>{item.name}</Text>
            )}
            getItemLayout={(data, index) => ({
              length: 80,
              offset: 80 * index,
              index,
            })}
            removeClippedSubviews={true}
            maxToRenderPerBatch={windowSize}
            windowSize={windowSize}
            numColumns={1}
            keyExtractor={(item, index) => String(index)}
            contentContainerStyle={{ paddingBottom: 10 }}
          />
        </ScrollView>
      </SafeAreaView>
    </View>
  );
};

export default Main;

我的数据已经排序,我想要这样:如果数据以字母A开头,那么这些数据应该包含在A标题部分中;如果数据以字母B开头,那么这些数据应该包含在B标题部分中。

就像这样,D标题只包含以D开头的数据,C标题只包含以C开头的数据。

但我不知道如何设置标题以及如何将数据放入标题部分。

简而言之,我想要的效果如下所示:

如何在React Native中以字母顺序设置标题?

有人能给我一个解决方案吗?

谢谢!🎊


<details>
<summary>英文:</summary>

# **output**

[![enter image description here](https://i.stack.imgur.com/0PkVA.jpg)](https://i.stack.imgur.com/0PkVA.jpg)

# **code**

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

import { nameData } from './dummydata';

const windowSize = FlatList.length > 50 ? FlatList.length / 4 : 21;

const Main = () => {
return (
<View style={{}}>
<SafeAreaView style={{}}>
<ScrollView style={{}}>

      &lt;FlatList
        disableVirtualization={true}
        //data={nameData.sort((a, b) =&gt; a.name.localeCompare(b.name))}
        data={nameData.sort(function (a, b) {
          return (a.name &lt; b.name) ? -1 : (a.name &gt; b.name) ? 1 : 0;
        })}
        renderItem={({ item }) =&gt; (
          &lt;Text style={{ fontSize: 20,marginLeft:10,padding:5 }}&gt;{item.name}&lt;/Text&gt;
        )}
      
        getItemLayout={(data, index) =&gt; ({
        length: 80,
        offset: 80 * index,
        index,
        })}
        removeClippedSubviews={true}
        maxToRenderPerBatch={windowSize}
        windowSize={windowSize}
        numColumns={1}
        keyExtractor={(item, index) =&gt; String(index)}
        contentContainerStyle={{ paddingBottom: 10 }}
      /&gt;

    &lt;/ScrollView&gt;
  &lt;/SafeAreaView&gt;
&lt;/View&gt;

);
};

export default Main;


**I have given the code above**

my data is sorted , I want like this if data is started A alphabet then this data contain in A header section if data is started B alphabet then this data contain in B header section.

like this D header contain only D Starting data C header contain only C Starting data

but I don&#39;t know how to set header and how to  set data in header section.

in sort I want like this data

[![enter image description here](https://i.stack.imgur.com/X8nvK.png)](https://i.stack.imgur.com/X8nvK.png)

anybody can give me solution?

**thank you!&#128060;**

</details>


# 答案1
**得分**: 0

**方法1**

尝试使用这个包 [react-native-section-alphabet-list][1]。

一个简单的React Native组件,它接受一个数据数组并以字母顺序(或自定义顺序)渲染一个SectionList。

**方法2**

更新您的代码如下并尝试:

```javascript
import React, { useEffect, useState } from "react";
import { Text, View, FlatList, SafeAreaView } from "react-native";

import { nameData } from "./duumydata";

const windowSize = FlatList.length > 50 ? FlatList.length / 4 : 21;

const Main = () => {
  let listData = new Array(26).fill([]);
  const headerArray = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];

  const [data, setData] = useState([]);

  useEffect(() => {
    nameData.sort(function (a, b) {
      return a.name.toUpperCase() < b.name.toUpperCase()
        ? -1
        : a.name > b.name
        ? 1
        : 0;
    });
    headerArray.forEach((header, index) => {
      nameData.forEach((item) => {
        const headerText = item.name.split("")[0].toUpperCase();
        if (header == headerText) {
          listData[index] = [...listData[index], item];
        }
      });
    });
    setData(listData);
  }, []);

  const renderItem = ({ item, index }) => {
    return (
      <>
        <View style={{ backgroundColor: "grey" }}>
          <Text>{headerArray[index]}</Text>
        </View>
        {item?.map((obj) => renderName(obj))}
      </>
    );
  };

  const renderName = (item) => {
    return (
      <View>
        <Text>{item.name}</Text>
      </View>
    );
  };

  return (
    <View style={{}}>
      <SafeAreaView style={{}}>
        <FlatList
          disableVirtualization={true}
          data={data}
          renderItem={(item) => renderItem(item)}
          getItemLayout={(data, index) => ({
            length: 80,
            offset: 80 * index,
            index
          })}
          removeClippedSubviews={true}
          maxToRenderPerBatch={windowSize}
          windowSize={windowSize}
          numColumns={1}
          keyExtractor={(item, index) => String(index)}
          contentContainerStyle={{ paddingBottom: 10 }}
        />
      </SafeAreaView>
    </View>
  );
};

export default Main;
英文:

Method 1

Try this package react-native-section-alphabet-list

A simple React Native component that takes an array of data and renders a SectionList with alphabetically (or custom) sorted data.

如何在React Native中以字母顺序设置标题?

Method 2

Update your code like below and try

import React, { useEffect, useState } from &quot;react&quot;;
import { Text, View, FlatList, SafeAreaView } from &quot;react-native&quot;;

import { nameData } from &quot;./duumydata&quot;;

const windowSize = FlatList.length &gt; 50 ? FlatList.length / 4 : 21;

const Main = () =&gt; {
  let listData = new Array(26).fill([]);
  const headerArray = [&quot;A&quot;,&quot;B&quot;,&quot;C&quot;,&quot;D&quot;,&quot;E&quot;,&quot;F&quot;,&quot;G&quot;,&quot;H&quot;,&quot;I&quot;,&quot;J&quot;,&quot;K&quot;,&quot;L&quot;,&quot;M&quot;,&quot;N&quot;,&quot;O&quot;,&quot;P&quot;,&quot;Q&quot;,&quot;R&quot;,&quot;S&quot;,&quot;T&quot;,&quot;U&quot;,&quot;V&quot;,&quot;W&quot;,&quot;X&quot;,&quot;Y&quot;,&quot;Z&quot;];

  const [data, setData] = useState([]);

  useEffect(() =&gt; {
    nameData.sort(function (a, b) {
      return a.name.toUpperCase() &lt; b.name.toUpperCase()
        ? -1
        : a.name &gt; b.name
        ? 1
        : 0;
    });
    headerArray.forEach((header, index) =&gt; {
      nameData.forEach((item) =&gt; {
        const headerText = item.name.split(&quot;&quot;)[0].toUpperCase();
        if (header == headerText) {
          listData[index] = [...listData[index], item];
        }
      });
    });
    setData(listData);
  }, []);

  const renderItem = ({ item, index }) =&gt; {
    return (
      &lt;&gt;
        &lt;View style={{ backgroundColor: &quot;grey&quot; }}&gt;
          &lt;Text&gt;{headerArray[index]}&lt;/Text&gt;
        &lt;/View&gt;
        {item?.map((obj) =&gt; renderName(obj))}
      &lt;/&gt;
    );
  };

  const renderName = (item) =&gt; {
    return (
      &lt;View&gt;
        &lt;Text&gt;{item.name}&lt;/Text&gt;
      &lt;/View&gt;
    );
  };

  return (
    &lt;View style={{}}&gt;
      &lt;SafeAreaView style={{}}&gt;
        &lt;FlatList
          disableVirtualization={true}
          data={data}
          renderItem={(item) =&gt; renderItem(item)}
          getItemLayout={(data, index) =&gt; ({
            length: 80,
            offset: 80 * index,
            index
          })}
          removeClippedSubviews={true}
          maxToRenderPerBatch={windowSize}
          windowSize={windowSize}
          numColumns={1}
          keyExtractor={(item, index) =&gt; String(index)}
          contentContainerStyle={{ paddingBottom: 10 }}
        /&gt;
      &lt;/SafeAreaView&gt;
    &lt;/View&gt;
  );
};

export default Main;

huangapple
  • 本文由 发表于 2023年1月9日 14:44:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75053910.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定