PermTree.js 1.7 KB
Newer Older
1
import React from 'react';
徐立's avatar
徐立 committed
2 3 4 5 6
import { Tree } from 'antd';

const TreeNode = Tree.TreeNode;

export default class PermTree extends React.Component {
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76
	constructor(props) {
		super(props);
		const value = props.value || {};
		this.state = {
			expandedKeys: [],
			autoExpandParent: true,
			ids: value.ids,
		};
	}

	onExpand = (expandedKeys) => {
		console.log('onExpand', expandedKeys);
		// if not set autoExpandParent to false, if children expanded, parent can not collapse.
		// or, you can remove all expanded children keys.
		this.setState({
			expandedKeys,
			autoExpandParent: false,
		});
	};

	onCheck = (ids) => {
		if (!('value' in this.props)) {
			this.setState({ ids });
		}
		this.triggerChange({ ids });
	};

	triggerChange = (changedValue) => {
		// Should provide an event to pass value to Form.
		const onChange = this.props.onChange;
		if (onChange) {
			onChange(Object.assign({}, this.state, changedValue));
		}
	};
	componentWillReceiveProps(nextProps) {
		// Should be a controlled component.
		if ('value' in nextProps) {
			const value = nextProps.value;
			this.setState(value);
		}
	}

	renderTreeNodes = (data) => {
		return data.map((item) => {
			if (item.children) {
				return (
					<TreeNode title={item.title} key={item.key} dataRef={item}>
						{this.renderTreeNodes(item.children)}
					</TreeNode>
				);
			}
			return <TreeNode {...item} />;
		});
	};

	render() {
		return (
			<Tree
				checkable
				selectable={false}
				onExpand={this.onExpand}
				expandedKeys={this.state.expandedKeys}
				autoExpandParent={this.state.autoExpandParent}
				onCheck={this.onCheck}
				checkedKeys={this.state.ids}>
				{this.renderTreeNodes(this.props.all)}
			</Tree>
		);
	}
}