ant-design/components/tree/demo/dynamic.md

82 lines
1.7 KiB
Markdown
Raw Normal View History

2015-10-27 15:47:01 +08:00
# 异步数据加载
- order: 3
异步加载数据
---
````jsx
import { Tree } from 'antd';
const TreeNode = Tree.TreeNode;
2015-10-27 15:47:01 +08:00
const asyncTree = [{
name: 'pNode 01',
key: '0-0'
}];
2015-10-27 15:47:01 +08:00
const generateTreeNodes = () => {
return [{
name: '伯约',
key: '0-0-0'
}];
};
2015-10-27 15:47:01 +08:00
const TreeDemo = React.createClass({
timeout(duration = 0) {
2015-12-27 16:20:59 +08:00
return new Promise((resolve) => {
setTimeout(resolve.bind(this), duration);
});
2015-10-27 15:47:01 +08:00
},
getInitialState() {
return {
treeData: []
};
},
componentDidMount() {
this.timeout(1000).then(() => {
this.setState({
treeData: asyncTree
});
return asyncTree;
});
},
handleSelect(info) {
console.log('selected', info);
},
handleDataLoaded(treeNode) {
return this.timeout(1000).then(() => {
const child = generateTreeNodes();
2015-10-27 15:47:01 +08:00
const treeData = [...this.state.treeData];
treeData.forEach((item) => {
if (item.key === treeNode.props.eventKey) {
item.children = child;
}
});
this.setState({treeData});
return child;
});
},
render() {
const loop = (data) => {
return data.map((item) => {
if (item.children) {
return <TreeNode title={item.name} key={item.key}>{loop(item.children)}</TreeNode>;
} else {
return <TreeNode title={item.name} key={item.key} />;
2015-10-27 15:47:01 +08:00
}
});
2015-10-27 15:47:01 +08:00
};
const parseTreeNode = data => loop(data);
2015-10-27 15:47:01 +08:00
let treeNodes = parseTreeNode(this.state.treeData);
return (
<Tree onSelect={this.handleSelect} onDataLoaded={this.handleDataLoaded} showLine={false}>
{treeNodes}
</Tree>
);
2015-10-27 15:47:01 +08:00
}
});
2015-10-27 15:47:01 +08:00
ReactDOM.render(<TreeDemo />, document.getElementById('components-tree-demo-dynamic'));
2015-10-27 15:47:01 +08:00
````