簡體   English   中英

如何在按鈕單擊時創建卡片?

[英]How do I create a card on button click?

我花了幾天時間學習 React JS。 它非常有趣並且簡化了 JavaScript,至少我是這么看的。 我目前的目標是創建一個按鈕,單擊該按鈕將創建一張新卡,並在卡中生成隨機數。

我不知道如何添加 onClick= 功能以使其按照我的設想工作。 目前,我的 index.js 文件中已編寫了按鈕的代碼。 index.js 是我的主文件,它是我的 App 組件所在的位置。 我看到人們使用一個名為 App.js 的文件,不知道為什么,但這是稍后的另一個問題。

目前我的按鈕采用以下方式進行風格化。

const App = () => {
  return (
    <body>
      <header>
        <div className="ui buttons">
          <button className="ui button mb-1 mt-1">
            <i className="plus icon"></i>
            Add Card
          </button>
          <div className="or mb-1 mt-1"></div>
          <button className="ui positive button mb-1 mt-1">
            <i className="sort numeric down icon"></i>
            Sort All
          </button>
        </div>
      </header>

它們位於我頁面頂部的 header 容器中。 如下圖所示。

添加卡片或排序所有按鈕標題

我希望能夠單擊“添加卡”按鈕,然后讓它在我的卡容器中創建一張新卡。 如下圖。

帶有添加卡片或排序所有按鈕的卡片容器可見。

您在上圖中看到的當前卡目前是硬編碼的。 我創建了一個 MainCard.js 組件,其中包含卡片的代碼,包括隨機生成的數字的功能和樣式。

import "bootstrap/dist/css/bootstrap.css";
import React from "react";
import { Card, Button } from "react-bootstrap";

let getRandomNumber = function (min, max) {
  let getRandom = Math.floor(Math.random() * max + min);
  return getRandom;
};

const MainCard = () => {
  return (
    <Card>
      <Button
        className="ui mini red basic icon button"
        style={{
          position: "absolute",
          top: "0",
          right: "0",
        }}
      >
        <i
          className="red x icon"
          style={{
            position: "relative",
            top: "0",
            right: "0",
          }}
        ></i>
      </Button>
      <Card.Body>{getRandomNumber(0, 101)}</Card.Body>
    </Card>
  );
};

export default MainCard;

以前我在我的 AddCard.js 中執行 onClick 功能,但由於某種原因,我創建的警報既是在重新加載頁面時生成的,也是在單擊按鈕時生成的。 我無法弄清楚其中的原因,它已成為我還無法爬過的牆。 我很確定我錯過了一些簡單的東西,但我就是不知道那是什么。 有什么想法可以實現這一目標嗎?

您需要使用useState()

例如。

import { useState } from "react";

export default function App() {
  const [{items}, setItems] = useState({ items: [] });
  const addItem = () => {
    items.push(<div key={items.length}>Hello</div>);
    setItems({ items: [...items] });
  };

  return (
    <div>
      <button onClick={addItem} />
      {items}
    </div>
  );
}

這將創建一個持久存儲,您可以將值設置為在組件重建之間保留的值。 存儲中的 object 具有單個鍵“項目”,其中包含項目的數組。 將您的 state 放入 object 並帶有描述內容的密鑰很方便。 如果您需要調試您的應用程序,這允許您告訴您正在查看的 state object。

addItem() 回調將在 state 中的 object 中添加一個新項目。 重要的是,該項目具有應該是唯一的關鍵屬性。 這有助於反應監視數組中元素的 state。

您可以在此處查看上述代碼的演示

正如 Charles Bamford 的回復所述,您必須使用 useState 方法。 useState 方法創建一個變量和一個設置該變量值的方法。 每次您更改 state(使用它的設置器)時,React 都會檢查代碼並在使用它的任何地方重新渲染。 你將需要這樣的東西:

const App = () => {
  const [cards, setCards] = useState([]); // instantiate cards as a empty Array

  const addCard = () => {
    // create a new array with the old values and the new random one
    const newCards = [...cards, Math.floor(Math.random() * 100)];

    setCards(newCards);
  };

  const removeCard = (cardIndex) => {
    // create a new array without the item that you are removing
    const newCards = cards.filter((card, index) => index !== cardIndex);

    setCards(newCards);
  };

  return (
    <body>
      <header>
        <div className="ui buttons">
          <button className="ui button mb-1 mt-1" onClick={() => addCard()}>
            <i className="plus icon"></i>
            Add Card
          </button>
          <div className="or mb-1 mt-1"></div>
          <button
            className="ui positive button mb-1 mt-1"
            onClick={() => addCard()}
          >
            <i className="sort numeric down icon"></i>
            Sort All
          </button>
        </div>
      </header>
      <main>
        {cards.map((cardNumber, index) => (
          <MainCard number={cardNumber} onRemove={() => removeCard(index)} />
        ))}
      </main>
    </body>
  );
};

使用這樣的數組 [10, 15, 33],cards.map 將為您執行以下操作:

  <main>
    <MainCard number={cards[0]} onRemove={() => removeCard(0)} /> // 10
    <MainCard number={cards[1]} onRemove={() => removeCard(1)} /> // 15
    <MainCard number={cards[2]} onRemove={() => removeCard(2)} /> // 33
  </main>

我們將“數字”和“onRemove”function 從 App 組件傳遞到 MainCard 組件。 現在我們只需要從我們的 props 中獲取它,就像這樣:

const MainCard = (props) => {
  const { onRemove, number } = props

  return (
    <Card>
      <Button
        className="ui mini red basic icon button"
        style={{
          position: "absolute",
          top: "0",
          right: "0",
        }}
        onClick={() => onRemove()}
      >
        <i
          className="red x icon"
          style={{
            position: "relative",
            top: "0",
            right: "0",
          }}
        ></i>
      </Button>
      <Card.Body>{number}</Card.Body>
    </Card>
  );
};

export default MainCard;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM