渲染一颗树(分别使用vue和react创建)

写代码要思路清晰,一步一步来,首先从最简单的来,慢慢加入新东西,逐渐优化。本文只是简单渲染出一颗树,通过传树形结构数组。

vue通过组件递归将数据渲染出一颗树,react则通过函数递归,

数据结构:

 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'}]}
]

  

渲染结果:

代码也简单

Vue(至少要两个组件才能看到效果)

tree组件(被调用):

<template>
    <div >
        <div>{{label}}</div>
        <vue-tree v-for="node in children" :label="node.label" :children="node.children"></vue-tree>
    </div>
</template>

<script>
export default {
    name:'vue-tree',
    props:['label','children']
}
</script>

home(调用tree)

<template>
  <div>
    <vue-tree :label="treeData.label" :children="treeData"></vue-tree>
  </div>
</template>

<script>
import VueTree from './VueTree';
export default {
  name: 'Home',
  data () {
    return {
     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'}]}]
    }
  },
  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'}]}]


class App extends Component {
  constructor(props) {
		super(props);
		this.state = { };
                this.buildTree=this.buildTree.bind(this);
  }
  buildTree(data){
    return data.map(item=>{
      if(item.children){
        return <div key={item.key}>{item.key}{this.buildTree(item.children)}</div>
      }
      return <div key={item.key}>{item.label}</div>
    })
  
  }
  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;
        

  下载地址:https://gitee.com/zhiming_2017/Components.git

 

posted @ 2018-09-08 21:17  mingL  阅读(489)  评论(0编辑  收藏  举报