我正在尝试为我的投资组合网站构建一个过滤器。复选框可让您选择一种技术(react、redux、jquery 等)来显示包含该技术的作品。因此,每次用户单击一个框时,我都想将值(JavaScript、Redux、React 等)添加到一个数组中,我在另一个函数中使用该数组来检查我的投资组合部分并过滤掉不存在的内容。
我发现这非常困难,但我认为它应该很简单。有人能指出我正确的方向吗?有没有一种方法可以简单地使用函数触发器(onChange 回调?)来读取表单输入元素的选中/未选中状态,然后相应地更新我的状态数组?我可以在 React 中简单地获取所有复选框的状态吗?我的复选框是否需要单独处于选中/未选中状态?
看起来 jQuery 使得选择器变得非常可能:
$('input[type="checkbox"]:checked').each(function () {}
最佳答案
如果您不关心顺序,而只想将项目添加到出现的数组中,我们绝对可以按照您在问题中建议的方式进行操作。在复选框的更改事件上,检查该框是否已选中或未选中(如果选中则 event.target.checked 返回 true,如果未选中则返回 false)并相应地处理数组逻辑。这是其工作原理的简单表示:
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>
)
}
}
如果您确实关心顺序,如果您可以像我在本示例中所做的那样将数值附加到数组中,您可以轻松地为复选框提供排序的数值,并且您可以在更新状态之前对数组进行排序,以便它始终处于特定状态无论检查顺序如何,都按顺序排列。
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 })
}
关于forms - 如何使用 React 和表单来获取选中的复选框值的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37129437/