从 querySelectorAll 反应 useRef

时间:2021-03-11 09:38:26

标签: javascript reactjs ref

我想用 Ref 完成这个简单的任务。首先,您填写要生成的按钮数量,然后当您单击偶数时,我想为所有具有偶数值的按钮添加类光,并在单击奇数时为奇数值添加类光。但是这种效果很简单,Vanilla JS 只需添加 querySelectorAll,然后单击添加或删除类灯,但在 React 中,我在理解这些引用案例时遇到了问题。什么时候只有一个 ref 我想怎么做,但是当我想生成几个时?

import React, { useState, useRef } from "react";
import "./style.css";

export default function App() {
  const [number, setNumber] = useState("");
  const evenButtonsRef = useRef([]);
  const oddButtonsRef = useRef([]);

  let buttons = [];
  const generateButtons = () => {
    for (let i = 1; i <= number; i++) {
      buttons.push(
        <button
          ref={i % 2 === 0 ? evenButtonsRef : oddButtonsRef}
          className={`${i % 2 === 0 ? "button even" : "button odd"}`}
        >
          {i}
        </button>
      );
    }
    return buttons;
  };

  const lightEvenButtons = () => evenButtonsRef.current.classList.add("light");

  const lightOddButtons = () => oddButtonsRef.current.classList.add("light");

  return (
    <div>
      <p>How many buttons?</p>
      <input
        type="text"
        onChange={e => setNumber(e.target.value)}
        placeholder="Number from 1 to 20"
      />
      {number && (
        <>
          <div className="button-group">
            <button onClick={lightEvenButtons}>Even</button>
            <button onClick={lightOddButtons}>Odd</button>
          </div>
          <div className="button-group">{generateButtons()}</div>
        </>
      )}
    </div>
  );
}

代码链接: https://stackblitz.com/edit/refbuttons?file=src/App.js

1 个答案:

答案 0 :(得分:1)

实际上你不需要在这里使用 refs。第一个原因是,最好保持状态哪些按钮应该突出显示(奇数或偶数)并根据状态设置适当的类。第二个原因是您不能将多个元素放入一个 ref 中,因此您需要拥有与按钮一样多的引用。

这是一个无需引用即可实现所需功能的代码:

import React, { useState, useRef } from "react";
import "./style.css";

export default function App() {
  const [number, setNumber] = useState("");
  const [highlightType, setHighlightType] = useState("");

  const renderButtons = () => {
    const buttons = [];
    for (let i = 1; i <= number; i++) {
      let className = `${i % 2 === 0 ? "button even" : "button odd"}`;
      if (highlightType === "odd" && i % 2 !== 0) {
        className = `${className} light`;
      }
      if (highlightType === "even" && i % 2 === 0) {
        className = `${className} light`;
      }
      buttons.push(
        <button
          key={i}
          className={className}
        >
          {i}
        </button>
      );
    }
    return buttons;
  };

  return (
    <div>
      <p>How many buttons?</p>
      <input
        type="text"
        onChange={e => setNumber(e.target.value)}
        placeholder="Number from 1 to 20"
      />
      {number && (
        <>
          <div className="button-group">
            <button onClick={() => setHighlightType("even")}>Even</button>
            <button onClick={() => setHighlightType("odd")}>Odd</button>
          </div>
          <div className="button-group">{renderButtons()}</div>
        </>
      )}
    </div>
  );
}

这里还有一个 working demorenderButtons 方法可能会有所改进,但我认为它清楚地展示了这个想法。