分别使用vue和react创建一个可伸缩的树
对前面树添加一个简单操作,点击可伸缩,对前面的代码改动了下
测试效果分别为(点击前面的+,即可伸展)
vue核心组件代码:
<template> <div > <div v-for="node in treeData"> <span v-if="node.children" @click="handleClick(node)">+</span> <strong >{{node.label}}</strong> <vue-tree :treeData="node.children" v-if="isKey===node.key && isshow"></vue-tree> </div> </div> </template> <script> export default { name:'vue-tree', props:['treeData'], data(){ return { isshow:false, isKey:'' } }, methods:{ handleClick(node){ this.isKey=node.key; console.log(this.isshow) this.isshow=!this.isshow; } } } </script>
测试效果代码为:
<template> <div> <vue-tree :treeData="treeData" ></vue-tree> </div> </template> <script> import VueTree from './VueTree'; export default { name: 'Home', data () { return { isshow:false, treeData:[ {label:'1',key:'1',children:[{label:'1-1',key:'11'},{label:'1-2',key:'12',children:[{label:'1-2-1',value:'121'}]}]}, {label:'2',key:'2',children:[{label:'2-1',key:'21'}]}] } }, components:{VueTree} } </script>
React核心组件:
import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; const treeData=[ {label:'1',key:'1',children:[{label:'1-1',key:'11'},{label:'1-2',key:'12'}]}, {label:'2',key:'2',children:[{label:'2-1',key:'21'}]}] // var isShow=true; class App extends Component { constructor(props) { super(props); this.state={ isShow:false, current:null } this.buildTree=this.buildTree.bind(this); this.collapse=this.collapse.bind(this); } buildTree(data){ return data.map(item=>{ if(item.children){ return <div> <span onClick={this.collapse}>+<span>{item.label}</span></span> <div style={{display:this.state.isShow &&this.state.current==item.label ?'block':'none'}}>{this.buildTree(item.children)}</div> </div> } return (<div key={item.key} >{item.label}</div>) }) } collapse(e){ this.setState({isShow:!this.state.isShow}); this.setState({current:e.target.children[0].innerHTML}) } render() { return ( <div className="App"> <header className="App-header"> <img src={logo} className="App-logo" alt="logo" /> <h1 className="App-title">Welcome to React</h1> </header> {this.buildTree(treeData)} </div> ); } } export default App;