我正在对页面进行条件呈现,并将用户在组件中可以查看的项目数限制为5。但是,我希望用户在点击更多时可以选择查看所有项目。
我尝试添加"查看更多"按钮以显示同一组件中的所有结果,但只有按钮显示,没有项目。当我console.log时,项目就在那里。我错过了什么让项目和按钮出现。
我的代码
,<Item.Group divided>
{
commentData !== ""?(
commentData.slice(0,5).map((data, index) => {
var x = new Date(data.comment_date)
data.comment_date = x.toDateString();
console.log('review---', data)
return (
<Item key={index}>
<Item.Content>
<Item.Description>By: {data.user_name} On : {data.comment_date} </Item.Description>
<Rating maxRating={5} defaultRating={data.rate} icon='star' size='large' />
<Item.Description>{data.comment}</Item.Description>
</Item.Content>
</Item>
);
}),
<Button color='red' onClick={() => {
commentData.map((data, index) => {
var x = new Date(data.comment_date)
data.comment_date = x.toDateString();
console.log('review---', data)
return (
<Item key={index}>
<Item.Content>
<Item.Description>By: {data.user_name} On : {data.comment_date} </Item.Description>
<Rating maxRating={5} defaultRating={data.rate} icon='star' size='large' />
<Item.Description>{data.comment}</Item.Description>
</Item.Content>
</Item>
);
})
}} > View More </Button>
):
<Header as='h2'>
Be the first one to review
</Header>
}
<Divider/>
您在这里采用了错误的方法,复制了代码。你应该使用你的状态,并在那里存储你想要显示的限制(在你的情况下是5(。单击该按钮时,应删除该值(例如设置为null(,然后根据状态呈现所有内容。这就是我对它的看法(认为它是伪代码(:
const [limit, setLimit] = useState(5);
return (
<>
items.slice(0, limit ? limit : items.length).map(item => /* render item logic */)
<button onClick={() => setLimit(null)}>Save</button>
</>