带有复选框选项的React Tree视图

时间:2017-02-21 06:35:34

标签: reactjs

如何使用checkbox中的react js选项创建树视图。 checkbox应放在树的右侧。

以下是创建treeiew的json示例:

var json = [
      { 
        "text": "Parent 1",
        "nodes": [
         { 
            "text": "Child 1",
            "nodes": [
              { 
                "text": "Grandchild 1"
              },
              {
                "text": "Grandchild 2"
              }
            ]
          },
          {
           "text": "Child 2"
          } 
        ]
      },
      {
       "text": "Parent 2"
      },
      {
       "text": "Parent 3"
      },
      {
       "text": "Parent 4"
      },
      {
        "text": "Parent 5"
      }
    ];

1 个答案:

答案 0 :(得分:0)

使用此递归函数来实现此目的:

_createList(item, margin){
      return item.map((el,i)=>{
          return <div key={i} style={{marginLeft: margin}}>
                   {el.text}
                   <input type='checkbox'/>
                   {el.nodes && el.nodes.length ? this._createList(el.nodes, 10) : null}
                 </div>
      })
  }

  render() {
    return (
      <div >
            {this._createList(json, 0)}
      </div>
    )
  }

检查工作fiddlehttps://jsfiddle.net/mayankshukla5031/rm49r11a/

var json = [
      { 
        "text": "Parent 1",
        "nodes": [
         { 
            "text": "Child 1",
            "nodes": [
              { 
                "text": "Grandchild 1",
                 "nodes": [
                     {
                        'text': 'G GrandChild1.1',
                        'nodes': [
                           {
                              'text': 'G G GrandChild1.1.1'
                           }
                        ]
                     },
                     {
                      	text: 'G GrandChild1.2'
                     }
                 ]
              },
              {
                "text": "Grandchild 2"
              }
            ]
          },
          {
           "text": "Child 2"
          } 
        ]
      },
      {
       "text": "Parent 2"
      },
      {
       "text": "Parent 3"
      },
      {
       "text": "Parent 4"
      },
      {
        "text": "Parent 5"
      }
    ];
class App extends React.Component {
  constructor() {
    super();
    this.state = {
    };
  }
  
  _createList(item, margin){
      return item.map((el,i)=>{
          return <div key={i} style={{marginLeft: margin}}>
                   {el.text}
                   <input defaultChecked type='checkbox'/>
                   {el.nodes && el.nodes.length ? this._createList(el.nodes, 10) : null}
                 </div>
      })
  }
  
  render() {
    return (
      <div >
        	{this._createList(json, 0)}
      </div>
    )
  }
}

ReactDOM.render(<App />, document.getElementById('container'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="container" ></div>