【发布时间】:2022-10-22 01:56:16
【问题描述】:
我对反应和使用状态挂钩很新鲜(仍在学习)。我想使用图像数组和 React 钩子创建显示更多/更少按钮。我将图像导入 div,我想在最后一个按钮上设置按钮,并在单击按钮时显示图像。
我收到错误:
text.slice 不起作用
问题是,代码是使用函数组件编写的。
这是我的代码:
import React from 'react'; import { useState } from 'react'; import '../assets/css/Product.css'; const ReadMore = ({ children }) => { const text = children; const [isReadMore, setIsReadMore] = useState(true); const toggleReadMore = () => { setIsReadMore(!isReadMore); }; return ( <p className='text'> {isReadMore ? text.slice(0, 150) : text} <span onClick={toggleReadMore} className='read-or-hide'> {isReadMore ? '...read more' : ' show less'} </span> </p> ); }; export const Product = () => { 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', }, ]; return ( <div> <div className='container'> <ReadMore> <div className='row introduction'> {card_image.map((card) => ( <div className='col-lg-3 pt-5'> <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' class='btn_product '> {card.button} </button> </div> </div> </div> ))} </div> </ReadMore> </div> </div> ); };
【问题讨论】:
-
请格式化您的代码!使用```你的代码在这里```
-
text.slice is not function因为你的文本不是字符串,如果你硬编码text = "Some Text"可以正常工作
标签: javascript reactjs