【问题标题】:not being able to console the data which is taken using UseRef() hook in react无法控制在反应中使用 UseRef() 钩子获取的数据
【发布时间】:2022-10-14 01:11:46
【问题描述】:

我有两张产品卡,每张卡都有自己的类别,如颜色、尺寸等,每张卡都有添加到购物车按钮。我使用 useRef() 钩子来获取用户选择的类别。并控制台它,当我单击添加到购物车按钮时。问题是我只有在按下两个按钮时才获得用户选择的第二个产品类别。请检查下面的代码。请随时要求澄清。

import "./Card.css";
import { useRef } from "react";

function Card() {
  const colorRef = useRef();
  const quantityRef = useRef();
  const sizeRef = useRef();

  const submitHandler = (event) => {
    event.preventDefault();

    const selectedColor = colorRef.current.value;
    const selectedQuantity = quantityRef.current.value;
    const selectedSize = sizeRef.current.value;

    const selectedData = {
      color: selectedColor,
      quantity: selectedQuantity,
      size: selectedSize
    };
    console.log(selectedData);
  };

  return (
    <div className="main-container">
      <div className="container">
        <div className="image-container">
          <img
            src="https://images.pexels.com/photos/9558601/pexels-photo-9558601.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            alt=""
          />
        </div>
        <h2> T-Shirt </h2>
      </div>
      <form className="form-conatiner" onSubmit={submitHandler}>
        <div className="selectors">
          <p>Solid Round Neck T-shirt</p>
          <select id="color" ref={colorRef} name="color" required>
            <option>Color</option>
            <option value="black">Black</option>
            <option value="green">Green</option>
            <option value="orange">Orange</option>
          </select>

          <select ref={quantityRef} name="qantity" required>
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>

          <select ref={sizeRef} name="size" required>
            <option>Size</option>
            <option value="medium">Medium</option>
            <option value="large">Large</option>
            <option value="small">Small</option>
          </select>
          <div>
            <button>Add to Cart</button>
          </div>
        </div>
      </form>
      <div className="container">
        <div className="image-container">
          <img
            src="https://images.pexels.com/photos/440320/pexels-photo-440320.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1"
            alt=""
          />
        </div>
        <h2> i-Watch </h2>
      </div>
      <div className="form-conatiner">
        <div className="selectors">
          <p>Dizo watch with amlod </p>
          <select id="2" ref={colorRef} name="color" required>
            <option>Brand</option>
            <option value="Apple">Apple</option>
            <option value="Samsung">Samsung</option>
            <option value="Pixel">Pixel</option>
          </select>

          <select ref={quantityRef} name="qantity" required>
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>

          <select ref={sizeRef} name="size" required>
            <option>size </option>
            <option value="29mm">29mm</option>
            <option value="34mm">34mm</option>
            <option value="42mm">42mm</option>
          </select>
          <div>
            <button onClick={submitHandler}>Add to Cart</button>
          </div>
        </div>
      </div>
    </div>
  );
}
export default Card;

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    这是预期的行为。 ref 将分配给第一个元素,然后分配给第二个元素。这就是为什么你总是最后一个。 第二个,你只用 form 标签包装了一个元素。

    为此,您应该使用useState 钩子和onChange 作为输入。比方说:

    function Card() {
      const [firstElement, setFirstElement] = useState({})
      const [secondElement, setSecondElement] = useState({})
      
      const handleFirstElementChange = (key, event) => {
        setFirstElement((oldState) => ({ ...oldState, [key]: event.target.value }))
      }
      
      const submitHandler = (event) => {
        event.preventDefault();
    
        console.log(firstElement, secondElement);
      };
      
      return <>
        <h2>T-shirt</h2>
        <select id="color" required onChange={(event) => handleFirstElementChange('color', event)>
          <option>Pick a color</option>
          <option value="black">Black</option>
          <option value="white">White</option>
          <option value="red">Ref</option>
        </select>
      </>
    }

    【讨论】:

    • 这很有帮助,而且效果很好。谢谢,但我实际上希望它用 useRef 本身来完成。相反,您使用了 useState。你能帮我用 useRef 做到这一点吗?
    【解决方案2】:

    您正在使用具有不同元素的相同 ref,因此它将引用最后一个元素,这就是为什么您总是获得第二个产品的引用 您应该尝试像这样使用 ref 数组

    const colorRef = useRef([]);
    const quantityRef = useRef([]);
    const sizeRef = useRef([]);
    

    并以这种方式传递(这是一种产品)

          <select id="color" ref={(el)=>{colorRef.current.push(el)}} name="color" required>
            <option>Color</option>
            <option value="black">Black</option>
            <option value="green">Green</option>
            <option value="orange">Orange</option>
          </select>
    
          <select ref={(el)=>{quantityRef.current.push(el)}}  name="qantity" required>
            <option>Quantity</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
          </select>
    
          <select ref={(el)=>{sizeRef.current.push(el)}}  name="size" required>
            <option>Size</option>
            <option value="medium">Medium</option>
            <option value="large">Large</option>
            <option value="small">Small</option>
          </select>
    

    然后在提交处理程序中像这样使用它

    常量 submitHandler = (事件) => { event.preventDefault();

    const selectedColor1 = colorRef.current[0].value;
    const selectedColor2 = colorRef.current[1].value;
    
    const selectedQuantity1 = quantityRef.current[0].value;
    const selectedQuantity2 = quantityRef.current[1].value;
    
    const selectedSize1 = sizeRef.current[0].value;
    const selectedSize2 = sizeRef.current[1].value;
    
    const selectedData1 = {
      color: selectedColor1,
      quantity: selectedQuantity1,
      size: selectedSize1
    };
    const selectedData2 = {
      color: selectedColor2,
      quantity: selectedQuantity2,
      size: selectedSize2
    };
    console.log(selectedData1);
    console.log(selectedData2);
     };
    

    一个工作的codesandbox 在这里。

    一个很好的排序阅读Here。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-27
      • 2020-12-03
      • 2020-02-03
      • 2021-11-02
      相关资源
      最近更新 更多