Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

javascript - Way to determine checkbox checked in react (useState)

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.

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 Checkbox A- Checked Checkbox B- Checked CheckedMap- A,B

T2 Checkbox B- Unchecked CheckedMap- A,B // Unticked Checkbox B is also stored in CheckedMap

Thank you for your help.

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)
                }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...