Javascript 如何单击按钮创建卡片?

Javascript 如何单击按钮创建卡片?,javascript,reactjs,bootstrap-4,onclick,card,Javascript,Reactjs,Bootstrap 4,Onclick,Card,我已经学了几天了。它非常有趣,简化了JavaScript,至少我是这么看的。我目前的目标是创建一个按钮,当点击该按钮时,将创建一张带有随机数的新卡 我不知道如何添加onClick=功能,让它按照我预想的方式工作。目前,我已经在index.js文件中编写了按钮的代码。index.js是我的主文件,它是我的应用程序组件所在的位置。我看到人们使用一个名为App.js的文件,不知道为什么,但这是后面的另一个问题 目前,我的按钮的样式如下 const App = () => { return (

我已经学了几天了。它非常有趣,简化了JavaScript,至少我是这么看的。我目前的目标是创建一个按钮,当点击该按钮时,将创建一张带有随机数的新卡

我不知道如何添加onClick=功能,让它按照我预想的方式工作。目前,我已经在index.js文件中编写了按钮的代码。index.js是我的主文件,它是我的应用程序组件所在的位置。我看到人们使用一个名为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>
const-App=()=>{
返回(
添加卡
全部排序
它们位于我的页面顶部的标题容器中

我希望能够单击“添加卡”按钮,然后在我的卡容器中创建一张新卡。如下图所示

您在上图中看到的当前卡目前是硬编码的。我创建了一个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;

import“bootstrap/dist/css/bootstrap.css”;
从“React”导入React;
从“react bootstrap”导入{Card,Button};
让getRandomNumber=函数(最小值、最大值){
让getRandom=Math.floor(Math.random()*max+min);
返回getRandom;
};
常量主卡=()=>{
返回(
{getRandomNumber(0,101)}
);
};
导出默认主卡;
以前我在我的AddCard.js中使用onClick功能,但由于某种原因,我创建的警报在页面重新加载时以及按钮被单击时都会生成。我无法理解原因,它已经变成了一堵我还无法翻过的墙。我很确定我错过了一些简单的东西,但我就是想不出那是什么。有什么想法我可以做到这一点吗?

你需要使用

比如说

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>
  );
}
从“react”导入{useState};
导出默认函数App(){
const[{items},setItems]=useState({items:[]});
常量附加项=()=>{
items.push(Hello);
setItems({items:[…items]});
};
返回(
{items}
);
}
这将创建一个持久性存储,您可以将值设置为组件重建之间的剩余值。存储中的对象有一个单键“items”使用包含项的数组。可以方便地将您的状态放在具有描述内容的键的对象中。这允许您在需要调试应用程序时告诉您正在查看的状态对象

addItem()回调将向处于状态的对象中添加一个新项。重要的是,该项具有一个应唯一的键属性。这有助于监视数组中元素的状态

您可以看到需要使用的上述代码的演示

比如说

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>
  );
}
从“react”导入{useState};
导出默认函数App(){
const[{items},setItems]=useState({items:[]});
常量附加项=()=>{
items.push(Hello);
setItems({items:[…items]});
};
返回(
{items}
);
}
这将创建一个持久性存储,您可以将值设置为组件重建之间的剩余值。存储中的对象有一个单键“items”使用包含项的数组。可以方便地将您的状态放在具有描述内容的键的对象中。这允许您在需要调试应用程序时告诉您正在查看的状态对象

addItem()回调将向处于状态的对象中添加一个新项。重要的是,该项具有一个应唯一的键属性。这有助于监视数组中元素的状态


您可以看到上述代码的演示,如Charles Bamford的回复所述,您必须使用useState方法。useState方法创建一个变量和一个方法来设置此变量的值。每次更改状态时(使用其setter)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>
  );
};
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;
const-App=()=>{
const[cards,setCards]=useState([]);//将卡实例化为空数组
const addCard=()=>{
//使用旧值和新随机值创建一个新数组
const newCards=[…cards,Math.floor(Math.random()*100)];
设置卡(新卡);
};
const removeCard=(cardIndex)=>{
//创建不包含要删除的项的新数组
const newCards=cards.filter((卡片,索引)=>index!==cardIndex);
设置卡(新卡);
};
返回(
addCard()}>
添加卡
addCard()}
>
全部排序
{cards.map((卡号,索引)=>(
removeCard(索引)}/>
))}
);
};
对于这样的数组[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>

removeCard(0)}///10
removeCard(1)}///15
removeCard(2)}///33
我们正在将“number”和“onRemove”函数从应用程序组件传递到主卡组件。现在我们只需从我们的道具中获取它,如下所示:

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>
  );
};
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;
const主卡=(道具)=>{
常量{onRemove,number}=props
返回(
onRemove()}
>
{number}
);
};
导出默认主卡;

如Charles Bamford的回复所述,您必须使用useState方法。useState方法创建一个变量和一个方法来设置此变量的值。每次更改