首页 > 解决方案 > 在引用数组中找到被点击的元素 (useRef)

问题描述

如果我有一个引用值数组,我如何找到点击的项目,我使用了 useRef

import { useRef, useState, useEffect } from 'react';

function App() {
  const checkboxes = useRef({});
  var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
  var myArrValues = []
  const [arrValues, setArrValues] = useState(false)

  for (let i = 0; i < arr.length; i++)
    myArrValues.push(i % 2 === 0)

  useEffect(() => {
    setArrValues(myArrValues)
  }, [])

  const setcheckBoxValue = (e) => {
    console.log(checkboxes);
  }

  return (
    <div className="App">
      {arr.map( (x, idx) =>
        <input 
          type="checkbox" 
          id={idx.toString()} 
          name={idx.toString()} 
          checked={arrValues[idx]}
          ref={ (el) => checkboxes.current[idx] = el } 
          onChange={(e) => setcheckBoxValue(e)}
        ></input>)
      }
    </div>
  );
}

export default App;

在 setcheckBoxValue 方法中,我需要知道单击了哪个复选框提前谢谢

拉斐尔

标签: javascriptreactjscheckboxcomponentsuse-ref

解决方案


我不认为 ref (或未arr使用的字符)在这里做任何有用的事情。如果要切换给定复选框的状态,只需跟踪在呈现闭包中迭代的索引,并在单击时将其传递:

const { useRef, useState, useEffect } = React;

function App() {
  const [arrValues, setArrValues] = useState(
    // use a function here to only create the initial array on mount
    () => Array.from(
      { length: 10 },
      (_, i) => i % 2 === 0
    )
  );

  const setcheckBoxValue = (i) => {
    setArrValues(
      arrValues.map((v, j) => j !== i ? v : !v)
    );
  }

  return (
    <div className="App">
      {arrValues.map( (val, i) =>
        <input 
          key={i}
          type="checkbox" 
          checked={val}
          onChange={() => setcheckBoxValue(i)}
        ></input>)
      }
    </div>
  );
}

ReactDOM.render(<App />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>


推荐阅读