简单实现多选功能并且获取选中内容
没什么含金量,凑合看吧。
先定义下
checkboxItems: [
{ content: "全部", checked: true },
{ content: "选项一", checked: false },
{ content: "选项二", checked: false },
{ content: "选项三", checked: false },
],
然后是展示部分,样式就自己写吧
{
this.state.checkboxItems.map((item, index) => {
return (
<span key={index}>
<span onClick={() => this.getVal(index)}
style={{ background: item.checked ? '#ECF2FD' : '',
color: item.checked ? "#437DF2" : '#4E5969' }}>
{item.content}</span>
</span>
)
})
}
点击事件的方法
getVal = (index) => {
//先复制一下
var items = [...this.state.checkboxItems]
//然后取反
items[index].checked = !items[index].checked
this.setState({
//更新checkboxItems
checkboxItems: items
})
//简单过滤
const resFind = this.state.checkboxItems.filter(item => item.checked === true);
let parseChecked = []
for (let i = 0; i < resFind.length; i++) {
parseChecked.push(resFind[i].content)
}
this.setState({
fundtpye: parseChecked
}, () => {
//最后拿到选中的值
console.log(this.state.fundtpye,);
})
}
然后用拿到的值做提交什么的就随便了,要是需要拿,拼再.join(',');一下,等等,巴拉巴拉。
就这些,来自一个摆烂萌新程序员的代码。