ElementGroup.js 1.89 KB
import React from 'react'
import Element from './Element'
import ReactAddonsUpdate from 'react-addons-update'

export default class ElementGroup extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      elements: [
        { id: 1, name: "药库", initialPos: {x: 80, y: 70}, target_type: 'RegionalDesign::Repo' },
        { id: 2, name: "药架", initialPos: {x: 80, y: 70 + 60}, target_type: 'RegionalDesign::DrugRepo' },
        { id: 3, name: "药架格", initialPos: {x: 80, y: 70 + 60 * 2}, target_type: 'RegionalDesign::DrugBrandreth' }
      ]
    };
    this.cloneElement = this.cloneElement.bind(this);
    this.deleteElement = this.deleteElement.bind(this);
    this.deleteLastElement = this.deleteLastElement.bind(this);
  }

  cloneElement(element) {
    const elements = ReactAddonsUpdate(this.state.elements, { $push: [element] })
    this.setState({elements: elements})
  }

  deleteElement(element) {
    const index = this.state.elements.indexOf(element)
    const elements = ReactAddonsUpdate(this.state.elements, { $splice: [[index, 1]] })
    this.setState({elements: elements})
  }

  // 返回element的index为-1, 删除最后一个元素
  deleteLastElement() {
    const elements = ReactAddonsUpdate(this.state.elements, { $splice: [[-1, 1]] })
    this.setState({elements: elements})
  }

  sidebar() {
    return document.getElementById('sidebar')
  }

  render() {
    return (
      <div>
        {
          this.state.elements.map(function(element) {
            return (
              <Element meta_element={ element } key={ "key_" + element.id } id={ element.id } name={ element.name } initialPos={ element.initialPos } target_type={ element.target_type } handleCloneElement={ this.cloneElement } handleDeleteElement={ this.deleteElement } handleDeleteLastElement={ this.deleteLastElement } />
            )
          }.bind(this))
        }
      </div>
    )
  }
}