[英]view more and view less with useState hook in react js
我对反应和使用状态挂钩很新鲜(仍在学习)。 我想使用图像数组和 React 钩子创建显示更多/更少按钮。 我将图像导入 div,我想在最后一个按钮上设置按钮,并在单击按钮时显示图像。
我收到错误消息:
text.slice 不是 function
问题是,代码是使用 function 组件编写的。
这是我的代码:
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>
);
};
我认为您应该使用条件渲染,这意味着当 state 发生变化时,您的 UI 也会发生变化。 抱歉,我认为我解释得不是很好,所以这里有一些示例代码。
import * from x "xyz xyz";
const App = () => {
const [showMore, setShowMore] = useState(false);
if(showMore){
return(
<MoreStuff/>
);
}
return(
<DefaultStuff/>
);
}
资源:
https://www.w3schools.com/react/react_conditional_rendering.asp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.