Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {useCallback, useState} from 'react';
- import {Button, Checkbox, Grid} from "@material-ui/core";
- import produce from "immer";
- TreeView.propTypes = {
- };
- const init_tree = [
- {id: 1, name: 'node1', checked: false, childrenNode: [
- {id: 12, name: 'node12', checked: false},
- {id: 13, name: 'node13', checked: false, childrenNode: [
- {id: 131, name: 'node131', checked: false},
- ]},
- ]},
- {id: 2, name: 'node2', checked: false, childrenNode: [
- {id: 21, name: 'node21', checked: false},
- {id: 22, name: 'node22', checked: false},
- {id: 23, name: 'node23', checked: false, childrenNode: [
- {id: 231, name: 'node231', checked: false},
- {id: 232, name: 'node232', checked: false},
- {id: 233, name: 'node233', checked: false},
- ]},
- ]},
- ]
- function useTree(init_tree = []){
- const [tree, setTree] = useState(init_tree)
- const getCurNode = (root, indexes)=>{
- const [n, ...left_indexes] = indexes
- let node = root[n]
- left_indexes.map(i=>{
- node = node?.childrenNode[i]
- })
- return node
- }
- const _setAllNodesChecked = (root, checked)=>{
- if(!root.hasOwnProperty('childrenNode')){return}
- root.childrenNode.map(node=>{
- node.checked = checked
- _setAllNodesChecked(node, checked)
- })
- }
- const toggleNode = useCallback((indexes)=>()=>{
- setTree(produce(prevTree=>{
- let node = getCurNode(prevTree, indexes)
- node.checked = !node.checked
- }))
- }, [])
- const setAllNodesChecked = useCallback((indexes, checked)=>()=>{
- setTree(produce(prevTree=>{
- let node = getCurNode(prevTree, indexes)
- node.checked = checked
- _setAllNodesChecked(node, checked)
- }))
- }, [])
- return {
- tree,
- toggleNode,
- setAllNodesChecked
- }
- }
- function TreeItem(props){
- const {tree, name, checked, indexes, childrenNode} = props
- return (
- <React.Fragment>
- <Grid container justifyContent={"space-between"}>
- <Grid item>
- <p style={{marginLeft: 16 * indexes.length}}>{name}</p>
- </Grid>
- <Grid item>
- <Checkbox checked={checked} onClick={tree.toggleNode(indexes)}/>
- <Button onClick={tree.setAllNodesChecked(indexes, true)}>全选</Button>
- <Button onClick={tree.setAllNodesChecked(indexes, false)}>取消全选</Button>
- </Grid>
- </Grid>
- {childrenNode?.map((item, index)=>(
- <TreeItem
- key={item.id}
- tree={tree}
- indexes={[...indexes, index]}
- {...item}
- />
- ))}
- </React.Fragment>
- )
- }
- function TreeView() {
- const tree = useTree(init_tree)
- return (
- <Grid container justifyContent={"center"}>
- <Grid item xs={6}>
- {tree.tree.map((item, index)=>(
- <TreeItem
- key={item.id}
- tree={tree} indexes={[index]}
- {...item}
- />
- ))}
- </Grid>
- </Grid>
- );
- }
- export default TreeView;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement