ElementGroup.js 1.7 KB
import React from 'react'
import Element from './Element'
import ReactAddonsUpdate from 'react-addons-update'
import autobind from 'autobind-decorator'
import { connect } from 'react-redux'

import { cloneElement, deleteLastElement } from '../actions/headergroup';

@autobind
class ElementGroup extends React.Component {
  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() {
    const { elements, cloneElement, deleteLastElement } = this.props
    return (
      <div>
        {
          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={ cloneElement } handleDeleteElement={ this.deleteElement } handleDeleteLastElement={ deleteLastElement } />
            )
          }.bind(this))
        }
      </div>
    )
  }
}

const mapStateToProps = (state, ownProps) => ({
  elements: state.headergroup
})

const mapDispatchToProps = (dispatch, ownProps) => ({
  cloneElement: (element) => {
    dispatch(cloneElement(element))
  },
  deleteLastElement: () => {
    dispatch(deleteLastElement())
  }
})

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(ElementGroup)