确定反应中已选中复选框的方法(useState) [英] Way to determine checkbox checked in react (useState)
问题描述
这是我第一次开发React应用程序.我试图在表格的每一行中实现复选框,并检查选中了哪些行.
This is my first time to develop a react application. I tried to implement checkboxes in each row of a table and check which of the rows are selected.
我使用了 useState
钩子来进行checked和onChange事件,但是当我选中然后取消选中该复选框时,值似乎没有刷新.
I used useState
hook to make checked and onChange events, but seems the values are not refreshing when I check then uncheck the checkbox.
我想问一下如何添加逻辑以删除钩子上未勾选的值.
I would like to ask how to add a logic to remove the unticked values on the hooks.
T1复选框A-已选中复选框B-已选中CheckedMap- A,B
T1 Checkbox A- Checked Checkbox B- Checked CheckedMap- A,B
T2复选框B-未选中CheckedMap- A,B//未选中的复选框B也存储在CheckedMap中
T2 Checkbox B- Unchecked CheckedMap- A,B // Unticked Checkbox B is also stored in CheckedMap
谢谢您的帮助.
export default function({ infinite }) {
const [checkedMap, setCheckedMap] = useState(new Map());
}
const handleCheckedChange = transaction_seq => {
let modifiedMap = checkedMap;
modifiedMap.set(transaction_seq, !checkedMap.get(transaction_seq));
setCheckedMap(modifiedMap);
};
const columns = [
{
Header: "Transaction(s)",
className: "left",
columns: [
{
id: "checkbox",
accessor: "checkbox",
Cell: ({ row }) => {
return (
<input
type="checkbox"
className="checkbox"
checked={checkedMap.get(row.original.transaction_seq)}
onChange={() =>
handleCheckedChange(row.original.transaction_seq)
}
推荐答案
这是将带有反应 useState
挂钩的受控复选框使用的方式.
This is the way how to use controlled checkbox with react useState
hook.
const { useState } = React; // --> for inline use
// import React, { useState } from 'react'; // --> for real project
const App = () => {
const [checked, setChecked] = useState(false)
const handleClick = () => setChecked(!checked)
return <input onClick={handleClick} checked={checked} type="checkbox" />
};
ReactDOM.render(<App />, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
这篇关于确定反应中已选中复选框的方法(useState)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!