需求设计
定义数据格式
[ [ { "flag": "false", "id": "96aea64d-5014-4479-98bd-64eac444e64a", "value": "尺码/颜色" }, { "flag": "false", "id": "9cf8e371-8738-4c61-acb4-a80b036bc44e", "value": "黑色/8056" }, { "flag": "false", "id": "60c009b3-b215-4761-acd4-77cd080c5e9a", "value": "秘釉色7475" } ], [ { "flag": "false", "id": "cf606eae-f535-48a0-a5d6-566979699a2d", "value": "165" }, { "flag": "false", "id": "3b868f1d-9dbf-4d55-acc7-eb170f071af7", "value": "" }, { "flag": "false", "id": "e5b4f621-f03b-4079-b34d-d99952764e00", "value": "" } ], [ { "flag": "false", "id": "a17a855b-8a3b-4202-813f-52a39dd6b183", "value": "170" }, { "flag": "false", "id": "204885f5-c786-4dfa-a949-3beb873d8b1f", "value": "" }, { "flag": "false", "id": "de183b17-8971-4735-9b03-0e9169bf672b", "value": "" } ], [ { "flag": "false", "id": "91923b21-bdaa-45fa-bf49-89286fefda75", "value": "175" }, { "flag": "false", "id": "9c3d73f8-b693-48fa-93b4-d36b43862728", "value": "" }, { "flag": "false", "id": "d578b782-0494-4223-9b5e-22106e7316f3", "value": "" } ], [ { "flag": "false", "id": "94a7a2c9-2f26-4bd5-83f8-7b3c691e9bef", "value": "160" }, { "flag": "false", "id": "b4a89ad8-2e35-4687-92e8-9b2b2b0206c9", "value": "" }, { "flag": "false", "id": "1ad8ca10-089a-4719-9782-b0f84e3c7dcd", "value": "" } ], [ { "flag": "false", "id": "2d5fcd60-cf7b-4bf7-bcd9-3cc9d91189d0", "value": "155" }, { "flag": "false", "id": "370e5ebf-3db5-4ce5-bfe6-8eb97601c27a", "value": "" }, { "flag": "false", "id": "a5654806-808a-469b-94e1-29d2fe6b2e28", "value": "" } ] ]
紧接着就是数据处理两层循环
<table style={{ border: "1px solid #ccc" }}> {dataListTest && dataListTest.map((outer: any, index: any) => ( <tr> {outer && outer.map((inner: any, num: any) => { if (num == 0 || index == 0) { return <th style={{ width: "5%", border: "1px solid #ccc", }}>{inner.value}</th> } else { return <th onClick={() => handleClick(inner)} style={{ width: "5%", border: "1px solid #ccc", }}>{inner.flag ? "✔" : inner.value}</th> } })} </tr> ))} </table>
需要进行两层循环 然后三元用来判断是否打勾 (num == 0 || index == 0)控制第一行和 第一列不可以点击
处理方法
const handleClick = (test: any) => { var dataList = JSON.parse(JSON.stringify(dataListTest)) for (const outer of dataList) { for (const inner of outer) { if (inner.id == test.id) { inner.flag = !inner.flag } } } console.log(dataList, "dataChange") setDataListTest(dataList) }
通过flag的true和false切换控制打勾
运行结果
总结
我是歌谣 放弃很容易 但是坚持一定很酷 微信公众号关注前端小歌谣 一起学习前端知识