antd Tree控件搜索功能
时间: 2024-05-08 21:17:05 浏览: 162
树形搜索控件
antd Tree控件提供了搜索功能,可以通过设置onSearch属性来实现。
首先,在Tree组件中添加一个Search组件,如下所示:
```jsx
import { Tree, Input } from 'antd';
const { Search } = Input;
class MyTree extends React.Component {
state = {
expandedKeys: [],
searchValue: '',
autoExpandParent: true,
};
onExpand = expandedKeys => {
this.setState({
expandedKeys,
autoExpandParent: false,
});
};
onChange = e => {
const { value } = e.target;
const expandedKeys = dataList
.map(item => {
if (item.title.indexOf(value) > -1) {
return getParentKey(item.key, this.props.treeData);
}
return null;
})
.filter((item, i, self) => item && self.indexOf(item) === i);
this.setState({
expandedKeys,
searchValue: value,
autoExpandParent: true,
});
};
render() {
const { treeData } = this.props;
const { searchValue, expandedKeys, autoExpandParent } = this.state;
const loop = data =>
data.map(item => {
const index = item.title.indexOf(searchValue);
const beforeStr = item.title.substr(0, index);
const afterStr = item.title.substr(index + searchValue.length);
const title =
index > -1 ? (
<span>
{beforeStr}
<span style={{ color: '#f50' }}>{searchValue}</span>
{afterStr}
</span>
) : (
<span>{item.title}</span>
);
if (item.children) {
return {
title,
key: item.key,
children: loop(item.children),
};
}
return {
title,
key: item.key,
};
});
return (
<div>
<Search style={{ marginBottom: 8 }} placeholder="Search" onChange={this.onChange} />
<Tree
onExpand={this.onExpand}
expandedKeys={expandedKeys}
autoExpandParent={autoExpandParent}
treeData={loop(treeData)}
/>
</div>
);
}
}
```
这里的onSearch函数会在Search组件的值发生变化时被调用。其中,onChange函数会根据搜索值来过滤出需要展开的节点,然后再将搜索值传递给loop函数,该函数会返回一个新的树形结构,其中匹配搜索值的节点会被高亮显示。
最后,在render函数中返回更新后的树形结构即可。
阅读全文