亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據按鈕 ID 進行過濾

根據按鈕 ID 進行過濾

弒天下 2023-10-14 11:11:08
我想過濾我的數據并根據單擊的按鈕動態顯示過濾后的數據。我的方法是創建一個變量并在按下按鈕時更新它并將該變量傳遞給過濾器函數,但是,這對我不起作用。有任何想法嗎?這是一個片段:var PageID = "0"const showPage = (event) =>{PageID = event.target.id}<button id = "1" onClick = {showPage}>1</button><button id = "2" onClick = {showPage}>2</button><button id = "3" onClick = {showPage}>3</button><button id = "4" onClick = {showPage}>4</button><button id = "5" onClick = {showPage}>5</button>{data.pages.filter(page => page.id == PageID).map(filteredid =>(  <li>    <div className="description_box">      <img src={filteredid.products[0].img}/>      <h2>{filteredid.products[0].title}</h2>      <p>{filteredid.products[0].description}</p>    </div>  </li>))}
查看完整描述

2 回答

?
慕斯王

TA貢獻1864條經驗 獲得超2個贊

我整理了一個工作示例。您需要將當前選擇存儲在狀態中:

import React, { useState } from "react";

import "./styles.css";


export default function App() {

? const [pageId, setPageId] = useState("0");


? const showPage = (event) => {

? ? setPageId(event.target.id);

? };


? const data = {

? ? pages: [

? ? ? {

? ? ? ? id: "1",

? ? ? ? products: [

? ? ? ? ? { img: "test", title: "Title 1", description: "Description 1" },

? ? ? ? ? { img: "test", title: "Title 2", description: "Description 2" }

? ? ? ? ]

? ? ? }

? ? ]

? };


? return (

? ? <>

? ? ? <button id="1" onClick={showPage}>

? ? ? ? 1

? ? ? </button>

? ? ? <button id="2" onClick={showPage}>

? ? ? ? 2

? ? ? </button>

? ? ? <button id="3" onClick={showPage}>

? ? ? ? 3

? ? ? </button>

? ? ? <button id="4" onClick={showPage}>

? ? ? ? 4

? ? ? </button>

? ? ? <button id="5" onClick={showPage}>

? ? ? ? 5

? ? ? </button>


? ? ? {data.pages

? ? ? ? .filter((page) => page.id === pageId)

? ? ? ? .map((filteredid) => (

? ? ? ? ? <li>

? ? ? ? ? ? <div className="description_box">

? ? ? ? ? ? ? <img src={filteredid.products[0].img} />

? ? ? ? ? ? ? <h2>{filteredid.products[0].title}</h2>

? ? ? ? ? ? ? <p>{filteredid.products[0].description}</p>

? ? ? ? ? ? </div>

? ? ? ? ? </li>

? ? ? ? ))}

? ? </>

? );

}


查看完整回答
反對 回復 2023-10-14
?
守著星空守著你

TA貢獻1799條經驗 獲得超8個贊

PageID應將其聲明為狀態以便具有反應性,然后使用它的設置器在按鈕單擊處理程序內進行更新:


const { PageID,setPageID} = React.useState('0')

const showPage = (event) =>{

setPageID(event.target.id)

}


查看完整回答
反對 回復 2023-10-14
  • 2 回答
  • 0 關注
  • 135 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號