te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Clear a list of checkboxes in React - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Clear a list of checkboxes in React - Stack Overflow

programmeradmin3浏览0评论

I have a few programatically generated lists of checkboxes (uncontrolled) in my project, and I'd like a react-way to clear them all at the click of a button. My problem is, I have no way to reference them each.

I've tried setting refs but I can't seem to figure out how to share refs between a stateless child and it's parent (is this even possible?)

All I need is a button that, when clicked, unchecks all checkboxes. I never would have imagined this would be so plicated but I've been at it for an hour now and my head is starting to spin. Here is an example of one of the lists:

{props.filters[0].map(jobType => (
  <li key={_.uniqueId('subType_')} className="checkbox text-sm m-b-sm">
    <label className="">
      <input type="checkbox" value={jobType.value} name="subtype" onChange={props.handleFilterCheck} />
      <span>{jobType.title}</span>
    </label>
    <span className="text-muted"></span>
  </li>
))}

So I have a way to consistently reference the size of the list and I know I could use iteration if I just had a way to reference the list but as it stands now that isn't possible. Any ideas?

I have a few programatically generated lists of checkboxes (uncontrolled) in my project, and I'd like a react-way to clear them all at the click of a button. My problem is, I have no way to reference them each.

I've tried setting refs but I can't seem to figure out how to share refs between a stateless child and it's parent (is this even possible?)

All I need is a button that, when clicked, unchecks all checkboxes. I never would have imagined this would be so plicated but I've been at it for an hour now and my head is starting to spin. Here is an example of one of the lists:

{props.filters[0].map(jobType => (
  <li key={_.uniqueId('subType_')} className="checkbox text-sm m-b-sm">
    <label className="">
      <input type="checkbox" value={jobType.value} name="subtype" onChange={props.handleFilterCheck} />
      <span>{jobType.title}</span>
    </label>
    <span className="text-muted"></span>
  </li>
))}

So I have a way to consistently reference the size of the list and I know I could use iteration if I just had a way to reference the list but as it stands now that isn't possible. Any ideas?

Share Improve this question edited Oct 4, 2017 at 18:09 Teivaz 5,6754 gold badges40 silver badges79 bronze badges asked Oct 4, 2017 at 17:48 Robbie MilejczakRobbie Milejczak 5,7803 gold badges35 silver badges68 bronze badges 3
  • 1 Create a state variable (an object) that contains any checked checkbox, so initially it will be empty, when a checkbox is checked, add it to the state variable, and if the special uncheck all box is checked, clear the state variable to its default (an object). – fungusanthrax Commented Oct 4, 2017 at 20:01
  • this is basically what I did! after creating a checkbox ponent, I added a state variable as a set, not an object and from there it was trivial to manage the state of the checkboxes. Thank you for the inspiration! – Robbie Milejczak Commented Oct 6, 2017 at 14:27
  • you know that's the best solution ;) – fungusanthrax Commented Oct 6, 2017 at 14:28
Add a ment  | 

4 Answers 4

Reset to default 8

I've tried setting refs but I can't seem to figure out how to share refs between a stateless child and it's parent (is this even possible?)

It's not possible with functional ponents. refs only work on class ponents.

The other suggestion would be to convert all the checkbox to controlled inputs and then use props to pass in the checked state of false.

Or move the checkbox into it's own ponent that handles its own state:

{props.filters[0].map(jobType => (
    <li key={_.uniqueId('subType_')} className="checkbox text-sm m-b-sm">
        <CheckBox 
            value={jobType.value} 
            label={jobType.title}  
            onChange={props.handleFilterCheck}
            checked={/* Here you can manually override the checked state by passing in a bool */}
        />
        <span className="text-muted"></span>
    </li>
))}


class CheckBox extends Component {
    constructor (props) {
        super(props);
        this.state = {
            checked: props.checked || false
        }
    }
    render() {
        const { value, title, handleFilterCheck } = this.props;
        const { checked } = this.state;
        return (
            <label className="">
                <input type="checkbox" value={value} name="subtype" onChange={handleFilterCheck} checked={checked} />
                <span>{title}</span>
            </label>
        )
    }
}

EDIT:

And last but not least, you can straight up target all the elements and set checked to false using pure JS and dom manipulation.

document.querySelectorAll('input[type=checkbox]').forEach( el => el.checked = false );

I managed to solve the same question by creating list of <Checkbox /> ponents. Then at parent level I used array state, which held all checked values. And one of the props to <Checkbox /> ponents was boolean which was telling if parent array state is empty.

const Parent = (someList) => {
  const [checkedArray,setCheckedArray] = useState([]);
  
  return(
    someList.map(el => <Checkbox key={el}
                                 empty={checkedArray.length === 0}
                                 value={el.value} /> 
                                 );
                                 );
                                 };
const Checkbox = ({empty, value}) => {
  const [checked, setChecked] = useState(false);
  
  useEffect(() => {
        empty && setChecked(false);
    }, [empty]);
    
  return(
    //some checkbox JSX
    );
    };

I'm newbie so there might be some pitfalls.

I came for this same problem, did a bit of thinking, and figured out a more "React" way.

I'm using checkboxes as a way to enter query parameters to call an api. We can use state to keep track of which checkboxes are currently checked. However, when rendering these checkboxes, we can set the checked attribute to be programmatically connected to our state. If the checkbox's value is in state, check it. Otherwise, don't.

We can then set up a button to reset this piece of state on click. Because state changes re-render the ponent, all of the checkboxes would re-render - setting checked to false.

const [selectedBoxes, setSelectedBoxes] = useState([]);
const renderCheckboxes = (items) => {
  return items.map(item => (
    <div key={item.id}>
      <input value={item.id} onChange={handleCheckbox} name="categories" checked={selectedBoxes.includes(item.id)} />
    </div>
  )
}
const handleCheckbox = (e) => {
  setSelectedBoxes([...selectedBoxes, e.target.value]);
}
return (
  <div>
    {renderCheckboxes()}
    <button onClick={setSelectedBoxes([])}>Click Me</button>
  </div>
)

Here is the trick in 2024! Passing the state to the input, not just the logic.

Instead of just

<input value={item.id} onChange={handleCheckbox} name="categories" 
checked={selectedBoxes.includes(item.id)} />

Use this selectedBoxes && selectedBoxes.includes(item.id)}:

<input value={item.id} onChange={handleCheckbox} name="categories" 
checked={selectedBoxes && selectedBoxes.includes(item.id)} />

This will trigger rerender when state of selectedBoxes changed.

发布评论

评论列表(0)

  1. 暂无评论