前端面试题之树结构数据标题修改(ts版本)
需求如下
当我们有如下图片的树结构
当我们点击的时候,可以修改其标题内容(这里可以用modal框,也可以用输入框),这里我是用的modal框
输入框输入的内容为我们的修改值,点击确定后,数据结构的title标题为我们的修改值,点击取消不修改其标题
点击确定后
代码如下:(因为在公司上班,所以依赖和引入库大家自行解决哈,so easy的)
import React, { useState } from 'react';
import { Tree, Modal, Input } from 'antd'
const treeData = [
{
title: '0-0',
key: '0-0',
children: [
{
title: '0-0-0',
key: '0-0-0',
children: [
{ title: '0-0-0-0', key: '0-0-0-0' },
{ title: '0-0-0-1', key: '0-0-0-1' },
{ title: '0-0-0-2', key: '0-0-0-2' },
],
},
{
title: '0-0-1',
key: '0-0-1',
children: [
{ title: '0-0-1-0', key: '0-0-1-0' },
{ title: '0-0-1-1', key: '0-0-1-1' },
{ title: '0-0-1-2', key: '0-0-1-2' },
],
},
{
title: '0-0-2',
key: '0-0-2',
},
],
},
{
title: '0-1',
key: '0-1',
children: [
{ title: '0-1-0-0', key: '0-1-0-0' },
{ title: '0-1-0-1', key: '0-1-0-1' },
{ title: '0-1-0-2', key: '0-1-0-2' },
],
},
{
title: '0-2',
key: '0-2',
},
];
const Test: React.FC = () => {
const [selectedKeys, setSelectedKeys] = useState<string>('');
const [modifyValue, setmodifyValue] = useState('')
const [modalVisible, setModalVisible] = useState(false)
const onSelect = (treeDateKey: string) => {
if (treeDateKey.length) {
setSelectedKeys(() => treeDateKey[0])
}
setModalVisible(true)
};
// 找元素的方法
let item: any = null
const getItem = (key: string, data: {}[]) => {
data.forEach((it: any) => {
if (it.key === key) {
item = it
return
}
else if (it.children) {
getItem(key, it.children)
}
})
return item
}
// 修改元素的方法
const modifyData = (data: {}[], modifyValue: string) => {
data.map((it: any) => {
if (it.key === getItem(selectedKeys, data).key) {
let c = it
c.title = modifyValue
return it
}
else if (it.children) {
modifyData(it.children, modifyValue)
}
})
setmodifyValue('')
}
const modalOnok = () => {
//修改treeDate的值
modifyData(treeData, modifyValue)
setModalVisible(false)
}
const modalOnCancel = () => {
setmodifyValue('')
setModalVisible(false)
}
return (
<>
<Tree
onSelect={onSelect}
treeData={treeData}
/>
<Modal title="修改标题" visible={modalVisible} onOk={modalOnok} onCancel={modalOnCancel}>
<p>标题</p>
<Input value={getItem(selectedKeys, treeData)?.title} disabled />
<p>修改内容</p>
<Input value={modifyValue} onChange={(e: any) => {
setmodifyValue(e.target.value)
}} />
</Modal>
</>
)
}
export default Test
有其他更好的方法,欢迎大家在评论区留言哈!!🙂🙂🙂