You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
2.6 KiB

# 异步数据加载
- order: 3
异步加载数据
---
````jsx
import { Tree } from 'antd';
const TreeNode = Tree.TreeNode;
9 years ago
import React from 'react';
9 years ago
function generateTreeNodes(treeNode) {
const arr = [];
const key = treeNode.props.eventKey;
for (let i = 0; i < 3; i++) {
arr.push({ name: `leaf ${key}-${i}`, key: `${key}-${i}` });
9 years ago
}
return arr;
}
9 years ago
function setLeaf(treeData, curKey, level) {
const loopLeaf = (data, lev) => {
const l = lev - 1;
data.forEach((item) => {
if ((item.key.length > curKey.length) ? item.key.indexOf(curKey) !== 0 :
curKey.indexOf(item.key) !== 0) {
return;
}
if (item.children) {
loopLeaf(item.children, l);
} else if (l < 1) {
item.isLeaf = true;
}
});
};
loopLeaf(treeData, level + 1);
}
9 years ago
function getNewTreeData(treeData, curKey, child, level) {
const loop = (data) => {
if (level < 1 || curKey.length - 3 > level * 2) return;
data.forEach((item) => {
if (curKey.indexOf(item.key) === 0) {
if (item.children) {
loop(item.children);
} else {
item.children = child;
}
}
});
9 years ago
};
loop(treeData);
setLeaf(treeData, curKey, level);
}
const Demo = React.createClass({
propTypes: {},
getInitialState() {
return {
9 years ago
treeData: [],
};
},
componentDidMount() {
9 years ago
setTimeout(() => {
this.setState({
9 years ago
treeData: [
{ name: 'pNode 01', key: '0-0' },
{ name: 'pNode 02', key: '0-1' },
{ name: 'pNode 03', key: '0-2', isLeaf: true },
9 years ago
],
});
9 years ago
}, 100);
},
9 years ago
onSelect(info) {
console.log('selected', info);
},
9 years ago
onLoadData(treeNode) {
return new Promise((resolve) => {
setTimeout(() => {
const treeData = [...this.state.treeData];
getNewTreeData(treeData, treeNode.props.eventKey, generateTreeNodes(treeNode), 2);
this.setState({ treeData });
9 years ago
resolve();
}, 500);
});
},
render() {
const loop = (data) => {
return data.map((item) => {
if (item.children) {
return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>;
}
9 years ago
return <TreeNode title={item.name} key={item.key} isLeaf={item.isLeaf} disabled={item.key === '0-0-0' ? true : false} />;
});
};
9 years ago
const treeNodes = loop(this.state.treeData);
return (
9 years ago
<div>
<h2>dynamic render</h2>
<Tree onSelect={this.onSelect} loadData={this.onLoadData}>
{treeNodes}
</Tree>
</div>
);
9 years ago
},
});
9 years ago
ReactDOM.render(<Demo />, mountNode);
````