javascript - 在引用数组中找到被点击的元素 (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 方法中,我需要知道单击了哪个复选框提前谢谢
拉斐尔
解决方案
我不认为 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>
推荐阅读
- r - 距离树以获得对人口结构的初步评估
- eclipse - 我必须在我的 Eclipse Web 项目中更改什么配置,以便 Tomcat 重定向 URL,而不需要任何指向项目 URL 的路径
- flutter - 收到错误“ParentDataWidget 使用不正确”。扑通扑通
- c# - 在我的嵌套 if 语句中我做错了什么吗?
- tabulator - 如何突出显示最大或最小数据?
- agda - 阿格达商店 Comonad
- python - curl --cacert vs python请求验证
- flutter - 在 Flutter 中保留状态的引用是否安全?
- c - Boehm GC 是否将 Win32 Fibers 堆栈识别为根?
- reactjs - 为什么蚂蚁设计抽屉不显示关闭图标?