zl程序教程

您现在的位置是:首页 >  前端

当前栏目

React技巧之检查复选框是否选中

React 技巧 是否 检查 选中 复选框
2023-06-13 09:11:16 时间

原文链接:https://bobbyhadz.com/blog/react-check-if-checkbox-is-checked[1]

作者:Borislav Hadzhiev[2]

正文从这开始~

总览

在React中,使用event对象上的target.checked 属性,来检查复选框是否选中。比如说,if (event.target.checked) {} 。或者在state变量中存储checked值,或者访问不受控制的复选框的ref.current.checked 属性。

import {useState} from 'react';

export default function App() {
  const [isSubscribed, setIsSubscribed] = useState(false);

  const handleChange = event => {
    if (event.target.checked) {
      console.log('✅ Checkbox is checked');
    } else {
      console.log('⛔️ Checkbox is NOT checked');
    }
    setIsSubscribed(current => !current);
  };

  return (
    <div>
      <label htmlFor="subscribe">
        <input
          type="checkbox"
          value={isSubscribed}
          onChange={handleChange}
          id="subscribe"
          name="subscribe"
        />
        Subscribe
      </label>
    </div>
  );
}

react-check-if-checkbox-checked-controlled.gif

如果对ref使用不受控制的复选框,请向下滚动到下一个代码片段。

event

event对象上的target属性引用input元素,因此我们可以通过event.target.checked来访问checked值。

需要注意的是,我们为setIsSubscribed传递了一个函数,因为该函数被保证以isSubscribed布尔值的当前(最新的)值来调用。

当我们需要基于当前state来计算下个state值时,这是非常有用的。

ref

要检查一个不受控制的复选框是否被选中,可以访问ref对象上的current.checked属性。

import {useRef} from 'react';

export default function App() {
  const ref = useRef(null);

  const handleClick = () => {
    if (ref.current.checked) {
      console.log('✅ Checkbox is checked');
    } else {
      console.log('⛔️ Checkbox is NOT checked');
    }
  };

  return (
    <div>
      <label htmlFor="subscribe">
        <input ref={ref} type="checkbox" id="subscribe" name="subscribe" />
        Subscribe
      </label>

      <br />

      <button onClick={handleClick}>Click</button>
    </div>
  );
}

check-if-checkbox-checked-uncontrolled.gif

useRef()钩子可以传递一个初始值作为参数。该钩子返回一个可变的ref对象,其.current属性被初始化为传递的参数。需要注意的是,我们必须访问ref对象上的current属性,来访问设置了ref属性的复选框元素。

当我们为元素传递ref属性时,比如说,<input ref={myRef} /> ,React将ref对象的.current属性设置为对应的DOM节点。每当点击button按钮时,handleClick函数就会被调用,同时检查复选框是否被选中。

useRef钩子创建了一个普通的JavaScript对象,但在每次渲染时都给你相同的ref对象。换句话说,它几乎是一个带有.current属性的记忆化对象值。

你可以在复选框元素上通过ref.current 访问任意属性。如果你打印ref对象上的current属性,你会发现它只是对input元素的引用。

参考资料

[1]

https://bobbyhadz.com/blog/react-check-if-checkbox-is-checked: https://bobbyhadz.com/blog/react-check-if-checkbox-is-checked

[2]

Borislav Hadzhiev: https://bobbyhadz.com/about