ModalRepoForm.js 2.43 KB
import React from 'react'
import { Modal, Button } from 'react-bootstrap'
import { Form, FormGroup, Col, FormControl, ControlLabel } from 'react-bootstrap'
import EventEmitter from '../libs/eventEmitter'
import $ from 'jquery'

export default class ModalRepoForm extends React.Component {
  constructor(props){
    super(props);
    this.state = {
      showModal: false, name: ''
    };
    this.close = this.close.bind(this);
    this.open = this.open.bind(this);
    this.handleChange = this.handleChange.bind(this);
  }

  close() {
    this.setState({ showModal: false })
  }

  open() {
    this.setState({ showModal: true })
  }

  handleChange(e) {
    return this.setState({ name: e.target.value })
  }

  save(e) {
    if (this.refs.name.value.trim().length === 0) {
      this.setState({ showNameError: true })
      return false
    } else {
      this.setState({ showNameError: false })
      e.preventDefault()
      $.post('/regional_design/repos.json', { repo: this.state }, function(data) {
        this.props.handleNewRepo(data)
        this.setState(this.getInitialState())
        EventEmitter.dispatch('alert', '操作成功')
      }.bind(this), 'JSON')
    }
  }

  render() {
    return (
      <div className='col-md-2'>
        <Button
          bsStyle="primary"
          bsSize="small"
          onClick={this.open}
        >
          新建仓库
        </Button>

        <Modal backdrop='static' show={this.state.showModal} onHide={this.close}>
          <Modal.Header closeButton>
            <Modal.Title>新建仓库</Modal.Title>
          </Modal.Header>
          <Modal.Body className='clearfix'>
            <form className='form-horizontal'>
              <label htmlFor="formHorizontalName" className="col-sm-2 control-label">仓库名</label>
              <div className="col-sm-5">
                <input autoFocus type="text" id="formHorizontalName" className="form-control" ref='name' value={ this.state.name } onChange={ this.handleChange } />
                {function(){
                  if (this.state.showNameError) {
                    return <p className="text-danger">仓库名不能为空</p>
                  }
                }.call(this)}
              </div>
            </form>
          </Modal.Body>
          <Modal.Footer>
            <Button bsStyle="primary" onClick={this.save}>保存</Button>
            <Button onClick={this.close}>关闭</Button>
          </Modal.Footer>
        </Modal>
      </div>
    )
  }
}