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.

98 lines
2.2 KiB

---
order: 1
title: 受控操作示例
---
9 years ago
受控操作示例
````jsx
import { Tree } from 'antd';
const TreeNode = Tree.TreeNode;
const x = 3;
const y = 2;
const z = 1;
const gData = [];
const generateData = (_level, _preKey, _tns) => {
const preKey = _preKey || '0';
const tns = _tns || gData;
const children = [];
for (let i = 0; i < x; i++) {
const key = `${preKey}-${i}`;
tns.push({ title: key, key });
9 years ago
if (i < y) {
children.push(key);
}
}
if (_level < 0) {
return tns;
}
const level = _level - 1;
9 years ago
children.forEach((key, index) => {
tns[index].children = [];
return generateData(level, key, tns[index].children);
9 years ago
});
};
generateData(z);
const Demo = React.createClass({
getDefaultProps() {
return {
9 years ago
multiple: true,
9 years ago
};
},
getInitialState() {
return {
expandedKeys: ['0-0-0', '0-0-1'],
autoExpandParent: true,
9 years ago
checkedKeys: ['0-0-0'],
selectedKeys: [],
};
},
onExpand(expandedKeys) {
console.log('onExpand', arguments);
// if not set autoExpandParent to false, if children expanded, parent can not collapse.
// or, you can remove all expanded chilren keys.
this.setState({
expandedKeys,
autoExpandParent: false,
});
9 years ago
},
9 years ago
onCheck(checkedKeys) {
9 years ago
this.setState({
9 years ago
checkedKeys,
9 years ago
selectedKeys: ['0-3', '0-4'],
});
},
9 years ago
onSelect(selectedKeys, info) {
console.log('onSelect', info);
this.setState({ selectedKeys });
9 years ago
},
render() {
const loop = data => data.map((item) => {
if (item.children) {
return (
<TreeNode key={item.key} title={item.key} disableCheckbox={item.key === '0-0-0'}>
9 years ago
{loop(item.children)}
</TreeNode>
);
}
return <TreeNode key={item.key} title={item.key} />;
});
return (
<Tree checkable multiple={this.props.multiple}
onExpand={this.onExpand} expandedKeys={this.state.expandedKeys}
autoExpandParent={this.state.autoExpandParent}
onCheck={this.onCheck} checkedKeys={this.state.checkedKeys}
onSelect={this.onSelect} selectedKeys={this.state.selectedKeys}>
9 years ago
{loop(gData)}
</Tree>
);
9 years ago
},
});
ReactDOM.render(<Demo />, mountNode);
````