在引用数组(useRef)中查找被单击的元素 [英] finding the clicked element in an array of references (useRef)

查看:81
本文介绍了在引用数组(useRef)中查找被单击的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个引用值数组,我使用useRef

How can I find the clicked item if I have an array of referenced values, I used 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方法中,我需要知道单击了哪个复选框预先感谢

In the setcheckBoxValue method, I need to know which checkbox was clicked Thanks in advance

拉斐尔

推荐答案

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

I don't think the ref (or the arr of unused characters) is doing anything useful here. If you want to toggle the state of a given checkbox, just keep track of the index being iterated over in the rendering closure, and pass it along when clicked:

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>

这篇关于在引用数组(useRef)中查找被单击的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆