syncfusion-react-listview

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Implementing Syncfusion React ListView

实现Syncfusion React ListView

A comprehensive guide to implementing the Syncfusion React ListView component for displaying dynamic, interactive lists with advanced features like templating, filtering, selection, and data management.
本文是一份全面指南,介绍如何实现Syncfusion React ListView组件,以展示具有模板、过滤、选择和数据管理等高级功能的动态交互列表。

When to Use This Skill

何时使用该技能

Use this skill when you need to:
  • Display lists of items with rich templating and customization
  • Implement single or multiple item selection
  • Add, remove, or update list items dynamically
  • Filter and search list data
  • Create nested or grouped lists
  • Handle user interactions (scroll, select, check)
  • Apply custom animations and styling
  • Support drag-and-drop operations
  • Optimize performance with virtualization
  • Implement data binding (local or remote)
  • Add checkboxes or custom icons
  • Provide accessibility features (WCAG 2.1)
当你需要以下功能时,可使用该技能:
  • 展示具有丰富模板和自定义功能的项列表
  • 实现单项或多项选择
  • 动态添加、删除或更新列表项
  • 过滤和搜索列表数据
  • 创建嵌套或分组列表
  • 处理用户交互(滚动、选择、勾选)
  • 应用自定义动画和样式
  • 支持拖拽操作
  • 通过虚拟化优化性能
  • 实现数据绑定(本地或远程)
  • 添加复选框或自定义图标
  • 提供无障碍功能(WCAG 2.1)

Component Overview

组件概述

The ListView component displays a collection of items in a scrollable, interactive list. It supports:
  • Data Sources: Arrays, objects, DataManager, remote APIs
  • Selection Modes: None, single, multiple, or checkbox-based
  • Templates: Item templates, header templates, group templates
  • Data Operations: Filtering, sorting, grouping, searching
  • Performance: Virtual scrolling for 1000+ items
  • Interactions: Click, select, scroll events
  • Styling: Built-in themes, custom CSS, RTL support
  • Accessibility: WCAG 2.1 Level AA compliant
ListView组件以可滚动的交互列表形式展示一组项,它支持:
  • 数据源: 数组、对象、DataManager、远程API
  • 选择模式: 无、单选、多选或基于复选框
  • 模板: 项模板、头部模板、分组模板
  • 数据操作: 过滤、排序、分组、搜索
  • 性能: 针对1000+项的虚拟滚动
  • 交互: 点击、选择、滚动事件
  • 样式: 内置主题、自定义CSS、RTL支持
  • 无障碍: 符合WCAG 2.1 AA级标准

Installation & Setup

安装与设置

Step 1: Install Syncfusion Packages

步骤1:安装Syncfusion包

bash
npm install @syncfusion/ej2-react-lists @syncfusion/ej2-base @syncfusion/ej2-data
bash
npm install @syncfusion/ej2-react-lists @syncfusion/ej2-base @syncfusion/ej2-data

Step 2: Import Required Modules

步骤2:导入所需模块

tsx
import { ListViewComponent } from '@syncfusion/ej2-react-lists';
// For additional features:
import { Inject, Virtualization } from '@syncfusion/ej2-react-lists';
tsx
import { ListViewComponent } from '@syncfusion/ej2-react-lists';
// 如需额外功能:
import { Inject, Virtualization } from '@syncfusion/ej2-react-lists';

Step 3: Import CSS

步骤3:导入CSS

tsx
import '@syncfusion/ej2-react-lists/styles/material.css'; // or other themes
tsx
import '@syncfusion/ej2-react-lists/styles/material.css'; // 或其他主题

Quick Start Example

快速入门示例

tsx
import React from 'react';
import { ListViewComponent } from '@syncfusion/ej2-react-lists';

export function BasicListView() {
  const data = [
    { id: '1', text: 'Item 1' },
    { id: '2', text: 'Item 2' },
    { id: '3', text: 'Item 3' }
  ];

  return (
    <ListViewComponent
      id="list"
      dataSource={data}
      fields={{ text: 'text', id: 'id' }}
    />
  );
}
tsx
import React from 'react';
import { ListViewComponent } from '@syncfusion/ej2-react-lists';

export function BasicListView() {
  const data = [
    { id: '1', text: 'Item 1' },
    { id: '2', text: 'Item 2' },
    { id: '3', text: 'Item 3' }
  ];

  return (
    <ListViewComponent
      id="list"
      dataSource={data}
      fields={{ text: 'text', id: 'id' }}
    />
  );
}

Core Concepts

核心概念

1. Data Binding

1. 数据绑定

Local Array:
tsx
const items = ['Apple', 'Banana', 'Orange'];
<ListViewComponent dataSource={items} />
Object Array with Mapping:
tsx
const data = [
  { productId: 1, productName: 'Laptop', category: 'Electronics' },
  { productId: 2, productName: 'Desk', category: 'Furniture' }
];

<ListViewComponent
  dataSource={data}
  fields={{
    id: 'productId',
    text: 'productName',
    groupBy: 'category'
  }}
/>
本地数组:
tsx
const items = ['Apple', 'Banana', 'Orange'];
<ListViewComponent dataSource={items} />
带映射的对象数组:
tsx
const data = [
  { productId: 1, productName: 'Laptop', category: 'Electronics' },
  { productId: 2, productName: 'Desk', category: 'Furniture' }
];

<ListViewComponent
  dataSource={data}
  fields={{
    id: 'productId',
    text: 'productName',
    groupBy: 'category'
  }}
/>

2. Selection Handling

2. 选择处理

tsx
const handleSelect = (args) => {
  console.log('Selected item:', args.text, args.id);
};

<ListViewComponent
  dataSource={data}
  select={handleSelect}
/>
tsx
const handleSelect = (args) => {
  console.log('选中的项:', args.text, args.id);
};

<ListViewComponent
  dataSource={data}
  select={handleSelect}
/>

3. Item Management

3. 项管理

  • Add Items:
    addItem(data, fields?)
  • Remove Items:
    removeItem(item)
  • Update Items: Replace in dataSource and refresh
  • Get Selection:
    getSelectedItems()
  • 添加项:
    addItem(data, fields?)
  • 删除项:
    removeItem(item)
  • 更新项: 替换数据源并刷新
  • 获取选中项:
    getSelectedItems()

4. Templates

4. 模板

tsx
// Item Template
const itemTemplate = (props) => (
  <div className="e-list-wrapper">
    <span>{props.text}</span>
    <span className="e-list-content">{props.category}</span>
  </div>
);

<ListViewComponent
  dataSource={data}
  fields={fields}
  template={itemTemplate}
/>
tsx
// 项模板
const itemTemplate = (props) => (
  <div className="e-list-wrapper">
    <span>{props.text}</span>
    <span className="e-list-content">{props.category}</span>
  </div>
);

<ListViewComponent
  dataSource={data}
  fields={fields}
  template={itemTemplate}
/>

Documentation & Navigation Guide

文档与导航指南

Getting Started

入门指南

📄 Read: references/getting-started.md
  • Installation and imports
  • Basic setup and first component
  • CSS themes and styling
  • Minimal working example
  • Project structure
📄 阅读: references/getting-started.md
  • 安装与导入
  • 基础设置与首个组件
  • CSS主题与样式
  • 最简可用示例
  • 项目结构

Data Binding & Rendering

数据绑定与渲染

📄 Read: references/data-binding-rendering.md
  • Local array data sources
  • Object mapping with fields
  • Remote data with DataManager
  • Query filtering on remote data
  • Load on demand and pagination
  • Dynamic data updates
📄 阅读: references/data-binding-rendering.md
  • 本地数组数据源
  • 对象与字段映射
  • 结合DataManager的远程数据
  • 远程数据的查询过滤
  • 按需加载与分页
  • 动态数据更新

Item Management (CRUD)

项管理(CRUD)

📄 Read: references/item-management.md
  • Adding new items dynamically
  • Removing items by reference
  • Updating existing items
  • Batch operations
  • Finding items in list
  • Managing nested list items
📄 阅读: references/item-management.md
  • 动态添加新项
  • 通过引用删除项
  • 更新现有项
  • 批量操作
  • 在列表中查找项
  • 管理嵌套列表项

Selection & Filtering

选择与过滤

📄 Read: references/selection-filtering.md
  • Single item selection
  • Multiple item selection
  • Checkbox-based selection
  • Programmatic selection
  • Filtering list items
  • Search functionality
  • Selection events and callbacks
📄 阅读: references/selection-filtering.md
  • 单项选择
  • 多项选择
  • 基于复选框的选择
  • 程序化选择
  • 列表项过滤
  • 搜索功能
  • 选择事件与回调

Templating & Customization

模板与自定义

📄 Read: references/templating-customization.md
  • Custom item templates (JSX, function, string)
  • Header templates with
    headerTemplate
  • Group header templates with
    groupTemplate
  • Template data context and variables
  • Dynamic templates based on device
  • CSS customization with classes
  • RTL template support
📄 阅读: references/templating-customization.md
  • 自定义项模板(JSX、函数、字符串)
  • 使用
    headerTemplate
    设置头部模板
  • 使用
    groupTemplate
    设置分组头部模板
  • 模板数据上下文与变量
  • 基于设备的动态模板
  • 结合类的CSS自定义
  • RTL模板支持

Advanced Features

高级功能

📄 Read: references/advanced-features.md
  • Grouping and sorting
  • Nested lists with hierarchy (up to 3 levels)
  • Checkbox state management
  • Animations and effects
  • Custom icons and image display
  • Enable/disable item states
📄 阅读: references/advanced-features.md
  • 分组与排序
  • 带层级的嵌套列表(最多3级)
  • 复选框状态管理
  • 动画与效果
  • 自定义图标与图片展示
  • 启用/禁用项状态

Performance & Virtualization

性能与虚拟化

📄 Read: references/performance-virtualization.md
  • Virtual scrolling for large datasets (1000+)
  • Enabling virtualization
  • Refresh item heights
  • Memory optimization tips
  • Combining with pagination
  • Performance best practices
  • Dataset size recommendations
📄 阅读: references/performance-virtualization.md
  • 针对大型数据集(1000+项)的虚拟滚动
  • 启用虚拟化
  • 刷新项高度
  • 内存优化技巧
  • 结合分页
  • 性能最佳实践
  • 数据集大小建议

API Reference & Properties

API参考与属性

📄 Read: references/api-reference.md
  • Complete property documentation
  • Method signatures and parameters
  • Event handler arguments
  • Default values for all properties
  • Property type specifications
  • Usage examples for each API
📄 阅读: references/api-reference.md
  • 完整的属性文档
  • 方法签名与参数
  • 事件处理程序参数
  • 所有属性的默认值
  • 属性类型规范
  • 每个API的使用示例

Accessibility & Events

无障碍与事件

📄 Read: references/accessibility-events.md
  • WCAG 2.1 compliance
  • Keyboard navigation
  • Screen reader support
  • ARIA attributes
  • Focus management
  • Event lifecycle
  • Event arguments and data
📄 阅读: references/accessibility-events.md
  • WCAG 2.1合规性
  • 键盘导航
  • 屏幕阅读器支持
  • ARIA属性
  • 焦点管理
  • 事件生命周期
  • 事件参数与数据

Common Patterns

常见模式

Pattern 1: List with Selection

模式1:带选择功能的列表

User clicks item → select event fires → update UI
tsx
const [selected, setSelected] = React.useState(null);

const handleSelect = (args) => {
  setSelected(args);
};

<ListViewComponent
  dataSource={items}
  select={handleSelect}
/>
用户点击项 → 触发选择事件 → 更新UI
tsx
const [selected, setSelected] = React.useState(null);

const handleSelect = (args) => {
  setSelected(args);
};

<ListViewComponent
  dataSource={items}
  select={handleSelect}
/>

Pattern 2: Add/Remove Items

模式2:添加/删除项

tsx
const listViewRef = React.useRef(null);

const addItem = () => {
  listViewRef.current.addItem([{ text: 'New Item', id: Date.now() }]);
};

const removeItem = (item) => {
  listViewRef.current.removeItem(item);
};

<ListViewComponent ref={listViewRef} dataSource={items} />
tsx
const listViewRef = React.useRef(null);

const addItem = () => {
  listViewRef.current.addItem([{ text: 'New Item', id: Date.now() }]);
};

const removeItem = (item) => {
  listViewRef.current.removeItem(item);
};

<ListViewComponent ref={listViewRef} dataSource={items} />

Pattern 3: Filtered List

模式3:过滤列表

tsx
const [filteredData, setFilteredData] = React.useState(items);

const handleFilter = (searchText) => {
  const filtered = items.filter(item =>
    item.text.toLowerCase().includes(searchText.toLowerCase())
  );
  setFilteredData(filtered);
};

<ListViewComponent dataSource={filteredData} />
tsx
const [filteredData, setFilteredData] = React.useState(items);

const handleFilter = (searchText) => {
  const filtered = items.filter(item =>
    item.text.toLowerCase().includes(searchText.toLowerCase())
  );
  setFilteredData(filtered);
};

<ListViewComponent dataSource={filteredData} />

Pattern 4: Multiple Selection with Checkboxes

模式4:带复选框的多项选择

tsx
<ListViewComponent
  dataSource={items}
  showCheckBox={true}
  fields={{ id: 'id', text: 'text', isChecked: 'checked' }}
/>
tsx
<ListViewComponent
  dataSource={items}
  showCheckBox={true}
  fields={{ id: 'id', text: 'text', isChecked: 'checked' }}
/>

Key Properties

关键属性

PropertyTypeDefaultPurpose
dataSource
Array/DataManager
[]
Data to display
fields
FieldSettingsModel
defaultMappedFields
Map data to fields
template
string/function/JSX
null
Custom item template
headerTemplate
string/function/JSX
null
Custom header template
groupTemplate
string/function/JSX
null
Custom group template
showCheckBox
boolean
false
Show checkboxes
checkBoxPosition
'Left'|'Right'
'Left'
Checkbox position
sortOrder
'None'|'Ascending'|'Descending'
'None'
Data sort order
enableVirtualization
boolean
false
Virtual scrolling
height
number|string
''
List height
width
number|string
''
List width
cssClass
string
''
Custom CSS class
enabled
boolean
true
Enable/disable component
enableRtl
boolean
false
Right-to-left support
animation
AnimationSettings
{...}
Item animations
属性类型默认值用途
dataSource
Array/DataManager
[]
要展示的数据
fields
FieldSettingsModel
defaultMappedFields
将数据映射到字段
template
string/function/JSX
null
自定义项模板
headerTemplate
string/function/JSX
null
自定义头部模板
groupTemplate
string/function/JSX
null
自定义分组模板
showCheckBox
boolean
false
显示复选框
checkBoxPosition
'Left'|'Right'
'Left'
复选框位置
sortOrder
'None'|'Ascending'|'Descending'
'None'
数据排序顺序
enableVirtualization
boolean
false
虚拟滚动
height
number|string
''
列表高度
width
number|string
''
列表宽度
cssClass
string
''
自定义CSS类
enabled
boolean
true
启用/禁用组件
enableRtl
boolean
false
从右到左支持
animation
AnimationSettings
{...}
项动画

Key Methods

关键方法

MethodPurpose
addItem(data, fields?)
Add new items to list
removeItem(item)
Remove item from list
removeMultipleItems(items)
Remove multiple items at once
selectItem(item)
Select an item
selectMultipleItems(items)
Select multiple items
unselectItem(item?)
Deselect item(s)
getSelectedItems()
Get current selection
findItem(item)
Find item details
checkItem(item)
Check a checkbox item
uncheckItem(item)
Uncheck checkbox item
checkAllItems()
Check all items
uncheckAllItems()
Uncheck all items
enableItem(item)
Enable disabled item
disableItem(item)
Disable item
hideItem(item)
Hide item
showItem(item)
Show hidden item
back()
Navigate back from nested list
refreshItemHeight()
Refresh item heights (virtualization)
destroy()
Clean up component
方法用途
addItem(data, fields?)
向列表添加新项
removeItem(item)
从列表中删除项
removeMultipleItems(items)
一次性删除多项
selectItem(item)
选中一项
selectMultipleItems(items)
选中多项
unselectItem(item?)
取消选中项
getSelectedItems()
获取当前选中项
findItem(item)
查找项详情
checkItem(item)
勾选复选框项
uncheckItem(item)
取消勾选复选框项
checkAllItems()
勾选所有项
uncheckAllItems()
取消勾选所有项
enableItem(item)
启用禁用项
disableItem(item)
禁用项
hideItem(item)
隐藏项
showItem(item)
显示隐藏项
back()
从嵌套列表返回上一级
refreshItemHeight()
刷新项高度(虚拟化场景)
destroy()
清理组件

Key Events

关键事件

EventTriggers When
select
Item is selected
actionBegin
Any action starts
actionComplete
Any action completes
actionFailure
Remote data fetch fails
scroll
User scrolls to top/bottom
事件触发时机
select
项被选中时
actionBegin
任何操作开始时
actionComplete
任何操作完成时
actionFailure
远程数据获取失败时
scroll
用户滚动到顶部/底部时

Common Use Cases

常见用例

  1. Display Settings List: Grouped items with icons
  2. Contact List: Multi-line templates with images
  3. Nested Navigation: Drill-down hierarchy
  4. Filterable Search: Dynamic data filtering
  5. Todo List: Checkboxes and item removal
  6. Product Catalog: Pagination and filtering
  7. Chat Messages: Reverse grouping by date
  8. Notification Feed: Scrolling with actions
  9. Multi-Select Picker: Checkboxes and buttons
  10. Hierarchical Menu: Nested items with back navigation
  1. 设置列表展示: 带图标的分组项
  2. 联系人列表: 带图片的多行模板
  3. 嵌套导航: 可钻取的层级结构
  4. 可过滤搜索: 动态数据过滤
  5. 待办事项列表: 复选框与项删除
  6. 产品目录: 分页与过滤
  7. 聊天消息: 按日期反向分组
  8. 通知信息流: 带操作的滚动列表
  9. 多选选择器: 复选框与按钮
  10. 层级菜单: 带返回导航的嵌套项

Tips & Best Practices

技巧与最佳实践

  • ✅ Always map
    fields
    correctly for data to display
  • ✅ Use templates for rich UI beyond plain text
  • ✅ Enable virtualization for 1000+ items
  • ✅ Use
    DataManager
    for filtering/sorting large remote data
  • ✅ Memoize templates and callbacks to prevent re-renders
  • ✅ Use
    cssClass
    for lightweight customization
  • ✅ Handle
    select
    event for user interactions
  • ✅ Clean up with
    destroy()
    when component unmounts
  • ❌ Don't render complex components in every item template
  • ❌ Don't forget to set proper
    fields
    mapping
  • ✅ 始终正确映射
    fields
    以确保数据正常展示
  • ✅ 使用模板实现纯文本之外的丰富UI
  • ✅ 针对1000+项启用虚拟化
  • ✅ 对大型远程数据使用
    DataManager
    进行过滤/排序
  • ✅ 对模板和回调进行记忆化处理以避免重复渲染
  • ✅ 使用
    cssClass
    进行轻量级自定义
  • ✅ 处理
    select
    事件以响应用户交互
  • ✅ 组件卸载时使用
    destroy()
    进行清理
  • ❌ 不要在每个项模板中渲染复杂组件
  • ❌ 不要忘记设置正确的
    fields
    映射

Troubleshooting

故障排除

Items not displaying?
  • Verify
    dataSource
    is populated
  • Check
    fields
    mapping matches data structure
  • Ensure
    text
    field is mapped correctly
Selection not working?
  • Verify
    select
    event handler is bound
  • Check item has valid
    id
    field
  • Ensure item is not disabled
Performance issues?
  • Enable
    enableVirtualization={true}
  • Reduce template complexity
  • Use
    DataManager
    for remote filtering instead of client-side
Styling issues?
  • Import CSS theme file
  • Check
    cssClass
    is applied to root element
  • Inspect CSS specificity conflicts

Next Steps:
  • Read appropriate reference files based on your use case
  • Check API Reference for complete property/method documentation
  • Review Accessibility guide for WCAG compliance
  • Explore code examples for your specific feature
项未显示?
  • 验证
    dataSource
    已填充数据
  • 检查
    fields
    映射是否与数据结构匹配
  • 确保
    text
    字段已正确映射
选择功能不生效?
  • 验证
    select
    事件处理程序已绑定
  • 检查项是否有有效的
    id
    字段
  • 确保项未被禁用
性能问题?
  • 启用
    enableVirtualization={true}
  • 降低模板复杂度
  • 对远程数据使用
    DataManager
    进行过滤,而非客户端过滤
样式问题?
  • 导入CSS主题文件
  • 检查
    cssClass
    是否应用到根元素
  • 检查CSS特异性冲突

下一步:
  • 根据你的用例阅读相应的参考文档
  • 查看API参考以获取完整的属性/方法文档
  • 查阅无障碍指南以确保WCAG合规
  • 探索针对特定功能的代码示例