如何使用React和Forms获取检查复选框值的数组? [英] How do I use React and forms to get an array of checked checkbox values?

查看:122
本文介绍了如何使用React和Forms获取检查复选框值的数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的投资组合网站建立一个过滤器。允许您选择一项技术(反应,redux,jquery等)的复选框,以显示包含该技术的作品。因此,每次用户单击一个框时,我都想将值(JavaScript,Redux,React等)添加到一个数组中,该数组用于另一个函数中以检查我的投资组合部分并过滤掉其中不存在的部分。

I am trying to build a filter for my portfolio website. Checkboxes that let you pick a technology (react, redux, jquery etc.) to display a piece of work(s) that contain(s) that/those technologies. So every time the user clicks on a box, I want to add the value (JavaScript, Redux, React etc.) to an array that I use in another function to check against my portfolio pieces and filter out what isn't there.

我发现这很困难,我认为这应该很简单。有人可以指出我正确的方向吗?有没有一种方法可以简单地使函数触发器(onChange回调?)读取表单输入元素的已检查/未检查状态,然后相应地更新状态数组?我可以在React中简单地获取所有复选框的状态吗?我的复选框是否需要分别处于选中状态/未选中状态?

I am finding this very difficult and I think it should be quite simple. Can someone point me in the right direction? Is there a way to simply have a function trigger (onChange callback?) that reads the checked/unchecked status of my form input elements and then updates my state array accordingly? Can I get the status of all the checkboxes simply in React? Do I need to have individual state of checked/unchecked for my checkboxes?

似乎jQuery使带有以下选择器的选择成为可能:

It seems that jQuery makes it pretty possible with selectors with:

$('input[type="checkbox"]:checked').each(function () {}


推荐答案

如果您不关心订单,而只想将商品附加到出现的数组上,我们绝对可以按照您在问题中的建议进行操作。更改复选框的事件,检查复选框是否被选中(event.target.checked如果被选中,则返回true;如果未选中,则返回false),并相应地处理数组逻辑。这是如何工作的简单表示:

If you don't care about the order and you just want to append the items to the array as they appear we could definitely do exactly what you suggest in your question. On the change event of the checkbox check if the box is checked or or unchecked (event.target.checked returns true if checked or false if unchecked) and handle the array logic accordingly. this is a simple representation of how that could work:

import React, { Component } from 'react'
import { connect } from 'react-redux'

class Portfolio extends Component {
  constructor() {
    super()
    // initialize your options array on your state
    this.state = {
      options: []
    }
  }

  onChange(e) {
    // current array of options
    const options = this.state.options
    let index

    // check if the check box is checked or unchecked
    if (e.target.checked) {
      // add the numerical value of the checkbox to options array
      options.push(+e.target.value)
    } else {
      // or remove the value from the unchecked checkbox from the array
      index = options.indexOf(+e.target.value)
      options.splice(index, 1)
    }

    // update the state with the new array of options
    this.setState({ options: options })
  }

  render() {
    return (
      <main className='portfolio'>

        <form>
          <div className="input-group">
            <label>cb1</label>
            <input type="checkbox" value={1} onChange={this.onChange.bind(this)} />
          </div>
          <div className="input-group">
            <label>cb2</label>
            <input type="checkbox" value={2} onChange={this.onChange.bind(this)} />
          </div>
          <div className="input-group">
            <label>cb3</label>
            <input type="checkbox" value={3} onChange={this.onChange.bind(this)} />
          </div>
        </form>

        <div className="selected-items">
          {this.state.options.map(number => 
             <p key={number}>item: {number}</p>
          )}
        </div>

      </main>
    )
  }
}

如果您确实关心订单,如果您可以像本例中那样将数值附加到数组中,则可以轻松地为复选框提供排序后的数值,并且可以在更新状态之前对数组进行排序,因此无论检查顺序如何,它始终处于特定顺序。

if you DO care about order, if you can append numerical values to the array like I did in this example you could easily give your checkboxes sorted numerical values and you could sort the array before updating your state so it's always in a certain order regardless of the order they are checked.

  onChange(e) {
    // current array of options
    const options = this.state.options
    let index

    // check if the check box is checked or unchecked
    if (e.target.checked) {
      // add the numerical value of the checkbox to options array
      options.push(+e.target.value)
    } else {
      // or remove the value from the unchecked checkbox from the array
      index = options.indexOf(+e.target.value)
      options.splice(index, 1)
    }

    // sort the array
    options.sort()    

    // update the state with the new array of options
    this.setState({ options: options })
  }

这篇关于如何使用React和Forms获取检查复选框值的数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆