【问题标题】:How select checkbox in Reactjs?如何在 Reactjs 中选择复选框?
【发布时间】:2020-06-05 05:20:10
【问题描述】:

我正在尝试当我单击一个复选框时,它应该被选中并将其值保存在 localstorage 中,这样如果页面被刷新,它应该从 localstorage 中获取值,同样对于第二个复选框,如果它也被选中然后也保存它在本地存储中的值为 true。

如果我选择两个复选框,即使在页面刷新后它也应该保留,这就是我想要的

这是我尝试过的代码

链接 - https://codesandbox.io/s/musing-architecture-p2nrg?file=/src/App.js:0-1760

import React from "react";
import "./styles.css";
import { Form } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";

export default function App() {
  const data = {
    naming: localStorage.getItem("naming") || false,
    fullname: localStorage.getItem("fullname") || false
  };
  const [currentCheckboxId, setCheckboxId] = React.useState(data);

  const setCheckbox = event => {
    const naming = event.target.checked;
    console.log(naming);
    localStorage.setItem("naming", naming);
    setCheckboxId({
      ...data,
      naming: event.target.checked
    });
  };

  const setCheckbox2 = event => {
    const fullname = event.target.checked;
    console.log(fullname);
    localStorage.setItem("fullname", fullname);
    setCheckboxId({
      ...data,
      fullname: event.target.checked
    });
  };

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <Form>
        <>
          <Form.Check
            onChange={setCheckbox}
            type="checkbox"
            label="Check me out"
            id="first"
            checked={currentCheckboxId.naming}
          />
          <Form.Group controlId="email">
            <Form.Label>Email Address</Form.Label>
            <Form.Control type="text" placeholder="Enter email" />
          </Form.Group>
        </>
        <>
          <Form.Check
            onChange={setCheckbox2}
            type="checkbox"
            label="Check me out"
            id="second"
            checked={currentCheckboxId.fullname}
          />
          <Form.Group controlId="fullname">
            <Form.Label>Name</Form.Label>
            <Form.Control type="text" placeholder="Enter name" />
          </Form.Group>
        </>
      </Form>
    </div>
  );
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    这是你需要做的:

    1. 初始化状态为false
    2. 使用useEffectmounted 上运行并从LocalStorage 中检索复选框值并相应地设置状态
    3. 使用setStateupdater function设置取决于当前状态的新状态
    export default function App() {
    
      // 1. Initially "false"
      const [currentCheckboxId, setCheckboxId] = React.useState({
        naming: false,
        fullname: false
      });
    
      // 2. useEffect to run @ mounted:
      // get from LS and update the state
      React.useEffect(() => {
        const data = {
          naming: localStorage.getItem('naming') === 'true' ? true : false,
          fullname: localStorage.getItem('fullname') === 'true' ? true : false
        };
        setCheckboxId(data);
      }, []);
    
      const setCheckbox = event => {
        const naming = event.target.checked;
        console.log('naming', naming);
        localStorage.setItem('naming', naming);
    
        // 3. use "function" with prevData as first argument to setState
        setCheckboxId(prevData => ({
          ...prevData,
          naming: naming
        }));
      };
    
      const setCheckbox2 = event => {
        const fullname = event.target.checked;
        console.log('fullname', fullname);
        localStorage.setItem('fullname', fullname);
    
        // 3. same as above
        setCheckboxId(prevData => ({
          ...prevData,
          fullname: fullname
        }));
      };
    
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
          <Form>
            <>
              <Form.Check
                onChange={setCheckbox}
                type="checkbox"
                label="Check me out"
                id="first"
                checked={currentCheckboxId.naming}
              />
              {/* Rest of your code */}
    }
    

    这是playground

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 2021-05-17
      相关资源
      最近更新 更多