使用 Javascript & 过滤按钮反应

发布于 2025-01-09 12:09:32 字数 4034 浏览 0 评论 0原文

再会!我希望能就我正在从事的项目获得一些帮助。我创建了一个过滤器功能,以便当用户单击按钮时,他们可以根据项目类型过滤我的项目。

我能够使“全部”按钮起作用,但其他按钮不起作用。 预期的输出是,当我单击按钮时,它会过滤掉其他项目并保留与类别匹配的项目。 然而,当前的输出是当我单击按钮时,项目消失。

这是我的代码:

    import React, {useState} from "react";
import ReactDOM from "react-dom";
import styles from "./projects.module.scss";
import cards from "./allData";


function Projects() {
 
  const [state, setState] = useState(cards);

  const handleBtns = (e) => {
      let word = e.target.value;
      function isCardActive() {
        for(const card of cards) {
            if (cards.category === "FEATURED") {
                return true;
            } else if (cards.category === "WEB APP") {
                return true;
            } else if (cards.category === "MOBLE APP"){
                return true
            }
        } 
      };

      if(word === 'All') { 
          setState(cards)
      } else if(word === 'Featured') {
          const filtered = cards.filter(isCardActive);
          setState(filtered);

    }  else if(word === 'webApp') {
        const filtered = cards.filter(isCardActive);
        setState(filtered);

  } else if(word === 'mobileApp') {
    const filtered = cards.filter(isCardActive);
    setState(filtered);
  }
}


    return(
        <div className={styles.projects} id="projectHash">
           <section>
               <h3>PROJECTS</h3>
            </section>

            
             <section id={styles.filterMain}>
            <button className={`${styles.filterBox} ${styles.active}`} onClick={handleBtns} type="button" value="All"  >VIEW ALL</button> 
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="Featured"  >FEATURED</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="webApp"  >WEB APP</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="mobileApp" >MOBILE APP</button>  
                 
            </section>

            <section>

           {state.map((cards) => (
                <div className={styles.projectcard} key={cards.id} >

                <h4>Project Name: {cards.title} </h4>
                <br/>
                <h4>{cards.image}</h4>
               
            </div>

           ))}
           </section>
            
        </div>
    )
};

export default Projects;

这是包含数据数组的文件的代码

import card1 from "../../assets/card1.jpg";
import card2 from "../../assets/card2.jpg";
import card3 from "../../assets/card3.jpg";
import card4 from "../../assets/card4.jpg";
import card5 from "../../assets/card5.jpg";
import card6 from "../../assets/card6.jpg";

 const cards = [
    {
        title: 'VICTORY FOLIO',
        category: ['WEB APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card1,
        id: 1

    },
    {
        title: 'IN WHOLENESS PRACTICE',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card2,
        id: 2
    },
    {
        title: 'TRIBE HAIRCARE',
        category: ['WEB APP', 'MOBILE APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card3,
        id: 3
    },
    {
        title: 'TRIBE SKINCARE',
        category: ['WEB APP', 'MOBILE APP'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card4,
        id: 4
    },
    {
        title: 'BUG TRACKER',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card5,
        id: 5
    },
    {
        title: 'PATIENT PORTAL',
        category: 'MOBILE APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card6,
        id: 6
    }

];

export default cards;

Good day! I am hoping to get some help with a project I am working on. I created a filter functionality so that when a user click on a button, they can filter my projects based on what type of project it is.

I was able to get the "ALL" button to work but the other buttons are not working.
The expected output is when I click on the button it filters out the other projects and keeps the one that matches the category.
However the current output is when I click on the button, the projects disappear.

This is my code:

    import React, {useState} from "react";
import ReactDOM from "react-dom";
import styles from "./projects.module.scss";
import cards from "./allData";


function Projects() {
 
  const [state, setState] = useState(cards);

  const handleBtns = (e) => {
      let word = e.target.value;
      function isCardActive() {
        for(const card of cards) {
            if (cards.category === "FEATURED") {
                return true;
            } else if (cards.category === "WEB APP") {
                return true;
            } else if (cards.category === "MOBLE APP"){
                return true
            }
        } 
      };

      if(word === 'All') { 
          setState(cards)
      } else if(word === 'Featured') {
          const filtered = cards.filter(isCardActive);
          setState(filtered);

    }  else if(word === 'webApp') {
        const filtered = cards.filter(isCardActive);
        setState(filtered);

  } else if(word === 'mobileApp') {
    const filtered = cards.filter(isCardActive);
    setState(filtered);
  }
}


    return(
        <div className={styles.projects} id="projectHash">
           <section>
               <h3>PROJECTS</h3>
            </section>

            
             <section id={styles.filterMain}>
            <button className={`${styles.filterBox} ${styles.active}`} onClick={handleBtns} type="button" value="All"  >VIEW ALL</button> 
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="Featured"  >FEATURED</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="webApp"  >WEB APP</button>
            <button className={styles.filterBox} onClick={handleBtns} type="button" value="mobileApp" >MOBILE APP</button>  
                 
            </section>

            <section>

           {state.map((cards) => (
                <div className={styles.projectcard} key={cards.id} >

                <h4>Project Name: {cards.title} </h4>
                <br/>
                <h4>{cards.image}</h4>
               
            </div>

           ))}
           </section>
            
        </div>
    )
};

export default Projects;

This is code for the file that contains the array of data

import card1 from "../../assets/card1.jpg";
import card2 from "../../assets/card2.jpg";
import card3 from "../../assets/card3.jpg";
import card4 from "../../assets/card4.jpg";
import card5 from "../../assets/card5.jpg";
import card6 from "../../assets/card6.jpg";

 const cards = [
    {
        title: 'VICTORY FOLIO',
        category: ['WEB APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card1,
        id: 1

    },
    {
        title: 'IN WHOLENESS PRACTICE',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card2,
        id: 2
    },
    {
        title: 'TRIBE HAIRCARE',
        category: ['WEB APP', 'MOBILE APP', 'FEATURED'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card3,
        id: 3
    },
    {
        title: 'TRIBE SKINCARE',
        category: ['WEB APP', 'MOBILE APP'],
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card4,
        id: 4
    },
    {
        title: 'BUG TRACKER',
        category: 'WEB APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card5,
        id: 5
    },
    {
        title: 'PATIENT PORTAL',
        category: 'MOBILE APP',
        description: 'Lorem ipsum dolro sit amt, consestcuer elit',
        image: card6,
        id: 6
    }

];

export default cards;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

吹泡泡o 2025-01-16 12:09:32

因此,这里面发生了很多事情,导致它无法工作,但基本上你的 isCardActive 什么也不做,因为它没有收到当前的卡片项目来进行比较。

我在此处创建了一个沙箱,说明它应该如何工作,使用 useState 和 useEffect 来当过滤器(currentCard)更改时过滤结果。我已经删除了样式,但是您可以很容易地将其添加回来。

代码在这里:

const [cards, setCards] = useState(allCards);
const [currentCard, setCurrentCard] = useState("All");

const handleBtns = (e) => {
  let word = e.target.value;
  setCurrentCard(word);
};

useEffect(() => {
  if (currentCard === "All") {
    setCards(allCards);
  } else {
    const filtered = allCards.filter((card) => {
      return (
        card.category === currentCard || card.category.includes(currentCard)
      );
    });
    setCards(filtered);
  }
}, [currentCard]);

return (
  <div className="App">
    <div id="projectHash">
      <section>
        <h3>PROJECTS</h3>
      </section>

      <section>
        <button onClick={handleBtns} type="button" value="All">
          VIEW ALL
        </button>
        <button onClick={handleBtns} type="button" value="FEATURED">
          FEATURED
        </button>
        <button onClick={handleBtns} type="button" value="WEB APP">
          WEB APP
        </button>
        <button onClick={handleBtns} type="button" value="MOBILE APP">
          MOBILE APP
        </button>
      </section>

      <h3>Current: {currentCard}</h3>

      <section>
        {cards.map((card) => (
          <div key={card.id}>
            <h4>Project Name: {card.title} </h4>
          </div>
        ))}
      </section>
    </div>
  </div>
);

So there's a whole lot going on in this that makes it not work, but basically your isCardActive does nothing because it doesn't receive the current card item to compare against.

I've created a sandbox here with how it should work, using useState and useEffect to filter the results when the filter (currentCard) changes. I've removed the styling, but you can add that back pretty easy.

And the code is here:

const [cards, setCards] = useState(allCards);
const [currentCard, setCurrentCard] = useState("All");

const handleBtns = (e) => {
  let word = e.target.value;
  setCurrentCard(word);
};

useEffect(() => {
  if (currentCard === "All") {
    setCards(allCards);
  } else {
    const filtered = allCards.filter((card) => {
      return (
        card.category === currentCard || card.category.includes(currentCard)
      );
    });
    setCards(filtered);
  }
}, [currentCard]);

return (
  <div className="App">
    <div id="projectHash">
      <section>
        <h3>PROJECTS</h3>
      </section>

      <section>
        <button onClick={handleBtns} type="button" value="All">
          VIEW ALL
        </button>
        <button onClick={handleBtns} type="button" value="FEATURED">
          FEATURED
        </button>
        <button onClick={handleBtns} type="button" value="WEB APP">
          WEB APP
        </button>
        <button onClick={handleBtns} type="button" value="MOBILE APP">
          MOBILE APP
        </button>
      </section>

      <h3>Current: {currentCard}</h3>

      <section>
        {cards.map((card) => (
          <div key={card.id}>
            <h4>Project Name: {card.title} </h4>
          </div>
        ))}
      </section>
    </div>
  </div>
);
漫漫岁月 2025-01-16 12:09:32

这是一个沙箱,其中包含我的解决方案,使用 useState hookcodesandbox

我要注意:

  1. 比较字符串值时,确保它们使用相同的格式/大写:
'Feature' === 'FEATURE' //false 
'FEATURE' === 'FEATURE' //true 
  1. 规范化对象中的数据。 JavaScript 是动态类型的,因此可以这样做:
card.category = 'string'
card.category = ['STRING']

确保数据类型相同,就无需在过滤器函数中进行额外的检查。

Here's a sandbox with my solution using the useState hook: codesandbox

I would note:

  1. When comparing string values, make sure that they use the same format/capitalization:
'Feature' === 'FEATURE' //false 
'FEATURE' === 'FEATURE' //true 
  1. Normalize data in your objects. JavaScript is dynamically typed, so it's ok to do this:
card.category = 'string'
card.category = ['STRING']

Making sure data types are the same removes the need to do extra checks in your filter function.

神回复 2025-01-16 12:09:32

您可以使用 Array.filter() 方法,还可以更改输入值以匹配类别,因为它们在卡片中定义为大写且之间有空格

const handleBtns = (e) => {
   const word = e.target.value;

   if (word === "All") setState(cards);
   else {
      const filteredCards = cards.filter(({ category }) => {
      return category.includes(word);
   });
   setState(filteredCards);
   }
 };

You can use Array.filter() method, also change the inputs values to match categories as they are defined in cards with uppercase and spaces between

const handleBtns = (e) => {
   const word = e.target.value;

   if (word === "All") setState(cards);
   else {
      const filteredCards = cards.filter(({ category }) => {
      return category.includes(word);
   });
   setState(filteredCards);
   }
 };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文