react hooks 动态增删模块

311 阅读1分钟

1.动态生产id

const getRandom = (num) =>{
  var random = Math.floor((Math.random()+Math.floor(Math.random()*9+1))*Math.pow(10,num-1));
  return Number(random)
}

2.创建动态生成的模块的 数据结构

const createData = () => {
    return {
        "cid": getRandom(9),
        "title": "菜单",
        "link_type": "",
        "customize_link_src": "",
        "factory_ids": []
    }
}

3.创建需要动态生成的模块的 结构

 const handleCreateBlock = (type: string) => {
    let item = {} as any
    switch (type) {
        case 'menu':
            item = createMenu()
            break;
    }
    return item
}

4.点击 新增 按钮

/**
 * 新增menu
 */
const handleAddBlock = () => {
    const _menu = handleCreateBlock('menu')
    handleUpdateValue({ ...section, 'blocks': [...menuBlocks, _menu] })
}
  1. 点击 删除 按钮
/**
 * 删除menu
 */
const handleDel = () => {
    const _cid = selectMenuBlock['cid']
    const _selectIndex = menuBlocks.findIndex((item: { cid: string; }) => item.cid === _cid)
    menuBlocks.splice(_selectIndex, 1)
    setShow(false)
    handleUpdateValue({ ...section, blocks: menuBlocks })
    setDelVisible(false)

}