首页 > 解决方案 > 如何在反应功能钩子中制作按钮组件,它可以接受输入以及加/减按钮值

问题描述

我正在尝试制作一个反应按钮组件,该组件具有加号和减号按钮以及用于插入所需数量的输入选项。我希望输入与加号和减号按钮一起使用。最后我有一个添加按钮,当我点击添加按钮时,它应该在购物车中更新。

我面临的问题是:

  1. 输入未按预期工作。我无法更正或输入输入。

  2. 我不想在输入字段中显示 0,但如果我setCount("");这样做会使初始状态变为空白并且加号按钮将无法按要求工作。

  3. 如何在handleValueChange().

  4. 我希望将代码重构为尽可能少的行,并且应该能够理解它(不浓缩)。

我非常感谢为改进而添加的任何其他代码。

沙盒链接——这里

如果可能的话,我可以参考一个工作沙箱,这将非常有帮助。

我的代码如下:

//App.jsx

import React, { useState } from "react";
import Qbutton from "./Qbutton";

function App() {
  return (
    <div>          
      <Qbutton />
    </div>
  );
}

export default App;

//数量按钮.jsx

import React, { useState } from "react";

function Qbutton(props) {
  const [count, setCount] = useState(0);
  const [error, setError] = useState(null);

  const Qty = 12;

  function handlePlus() {
    if (count < Qty) {
      setCount(count + 1);
      setError(null);
    } else {
      setError("No stock");
    }
  }

  function handleMinus() {
    if (count > 0) {
      setCount(count - 1);
      setError(null);
    } else {
      setError("No items in Cart");
    }
  }

  function handleValueChange(e) {
    const x = Number(e.target.value);
        
    if (isNaN(x) || x < 1 || x > Qty) {
      setError(
        "Input not valid"
      ); /*How to display/include handle plus & minus Error messages*/
    } else {
      setCount(x);
      setError("Qty updated");
    }
    console.log(x);
  }

  function SubmitQty(e) {
    setError("Items Added to Cart");        
    setCount(0);
    /* Delete setCount if u want the selected Quantity to show up.. Set it "0" if required it to get cleared*/
    e.preventDefault();
  }

  console.log(count);
  return (
    <div className="btnWrapper">
      <h1> Quantity Button </h1>

      <div className="counterDisplay">
        <button
          style={{ borderRadius: "25px 0px 0px 25px" }}
          onClick={handleMinus}
        >
          -
        </button>
        <input
          type="text"
          min="0"
          value={count}
          onClick={() => setCount(0)}
          onChange={handleValueChange}
        />
        <button onClick={handlePlus}>+</button>
        <button
          className="AddBtn"
          style={{ borderRadius: "0px 25px 25px 0px" }}
          onClick={SubmitQty}
        >
          Add
        </button>
      </div>
      {error}
    </div>
  );
}

export default Qbutton;

标签: javascriptreactjsreact-hooks

解决方案


App.js

import React, { useState } from "react";

import Qbutton from "./Qbutton";

function App() {
  // U should map the Qty in Qbutton.
  const [cart, setCart] = useState([]);

  function addItem(newItem) {
    console.log(newItem , "New Itemm")
    setCart((prevNotes) => {
      return [newItem];
    });
  }

  return (
    <div>
      <h1>Items in Cart: {cart + ""} </h1>
      <Qbutton onAdd={addItem} qty={6} />
    </div>
  );
}

export default App;






QtButton.js

import React, { useState } from "react";

function Qbutton(props) {
  const [count, setCount] = useState(null);
  const [error, setError] = useState(null);

  function handlePlus() {
    if(count === null || count === ""){
      setCount(1);
    } else {
      setCount(count + 1);
      setError(null);
    }
  }

  function handleMinus() {
    if (count > 0) {
      setCount(count - 1);
      setError(null);
    } else {
      setError("Please Enter a Valid Number");
    }
  }

  function handleValueChange(e) {
    e.preventDefault();
    const re = /^[0-9\b]+$/;
    if (e.target.value === "" || re.test(e.target.value)) {
      const x = Number(e.target.value);
      setCount(x);
      setError("Qty updated");
    } else {
      setError("Your input is not valid");
    }
  }

  function SubmitQty(e) {
    e.preventDefault();
    if (count !== 0 && count !== null) {
      props.onAdd(count);
      setError("Items Added to Cart");
      setCount("");
    } else {
      setError("Please Enter a Valid Number");
    }
    /* Delete setCount if u want the selected Quantity to show up.. Set it "0" 
      if required it to get cleared*/
  }

  return (
    <div className="btnWrapper">
      <h1> Quantity Button </h1>

      <div className="counterDisplay">
        <button
          style={{ borderRadius: "25px 0px 0px 25px" }}
          onClick={handleMinus}
        >
          -
        </button>
        <input
          type="text"
          min="0"
          value={count}
          onClick={() => setCount(null)}
          onChange={handleValueChange}
        />
        <button onClick={handlePlus}>+</button>
        <button
          className="AddBtn"
          style={{ borderRadius: "0px 25px 25px 0px" }}
          onClick={SubmitQty}
        >
          Add
        </button>
      </div>
      {error}
    </div>
  );
}

export default Qbutton;

推荐阅读