React用useState实现查看更多/更少报text.slice不是函数错误
报错根因
你当前使用的ReadMore组件是为长文本截断场景设计的,核心逻辑是对传入的children(预期为字符串/数组类型)调用slice()方法截取前150个字符。但你实际传入ReadMore的子元素是一整段图片卡片的JSX结构(React Element对象类型),对象本身不存在slice方法,因此触发text.slice is not function运行时报错。
同时你要实现的是图片列表的「部分展示/全部展示」切换,和文本截断的逻辑完全不匹配,原有ReadMore组件无法直接复用。
修复实现
直接在Product组件内通过useState维护列表展开状态,不需要套用文本截断组件,步骤如下:
- 定义初始默认展示的图片数量
- 声明状态控制列表是否全量展开
- 根据展开状态截取要渲染的图片数组片段
- 列表渲染完成后,在尾部放置切换按钮,点击时翻转展开状态,同时根据状态切换按钮文案
- 修复原代码中React语法问题:将button标签上的HTML原生
class属性改为React要求的className
修复后的完整可运行代码:
import React from 'react'; import { useState } from 'react'; import '../assets/css/Product.css'; export const Product = () => { // 初始默认展示4张卡片,可根据需求自行调整 const INITIAL_SHOW_COUNT = 4; const [isExpand, setIsExpand] = useState(false); const card_image = [ { image: 'CLT_Food_BeverageBar.jpg', title: 'Charlotte', subtitle: '(CLT)', button: 'Explore Lounge', }, { image: 'Centurion_Cropped_0001_Bar.jpg', title: 'Dallas', subtitle: '(DFW)', button: 'Explore Lounge', }, { image: 'DEN_GameRoom-LR_1200x540.jpg', title: 'Denver', subtitle: '(DEN)', button: 'Explore Lounge', }, { image: 'IAH_Bar&Buffet_1200x600.jpg', title: 'Houston', subtitle: '(IAH)', button: 'Explore Lounge', }, { image: 'amxtcl_Lounge_01_cmyk_1200x600.jpg', title: 'Las Vegas', subtitle: '(LAS)', button: 'Explore Lounge', }, { image: 'LAX_hero.jpg', title: 'Los Angeles', subtitle: '(LAX)', button: 'Explore Lounge', }, { image: 'LoungeAreaTalent1200x600.jpg', title: 'Miami', subtitle: '(MIA)', button: 'Explore Lounge', }, { image: 'JFK_Carousel_3.jpg', title: 'New York', subtitle: '(JFX)', button: 'Explore Lounge', }, ]; // 根据展开状态决定要渲染的列表 const renderCardList = isExpand ? card_image : card_image.slice(0, INITIAL_SHOW_COUNT); const toggleExpand = () => { setIsExpand(!isExpand); }; return ( <div> <div className='container'> <div className='row introduction'> {renderCardList.map((card, index) => ( <div className='col-lg-3 pt-5' key={index}> <div className='location_card' style={{ backgroundImage: `url(${process.env.REACT_APP_ASSET_URL}/card_image/${card.image})`, objectFit: 'cover', }}> <div className='location-overly'> <h3 className='h2'> {card.title} <br /> {card.subtitle} </h3> <button type='button' className='btn_product'> {card.button} </button> </div> </div> </div> ))} </div> {/* 列表尾部的控制按钮 */} <div className="text-center pt-4"> <span onClick={toggleExpand} className='read-or-hide' style={{cursor: 'pointer', color: '#0d6efd'}}> {isExpand ? '查看更少' : '查看更多'} </span> </div> </div> </div> ); };
补充说明:列表渲染时给每一项加了
key属性(用数组索引做key适配当前静态列表场景),避免React抛出列表key缺失的警告。
内容的提问来源于stack exchange,提问作者Uswa Nadeem
相关产品推荐
相关产品推荐

