无法在React-Bootstrap的Formgroup组件中获取表单值

时间:2017-05-30 08:16:47

标签: reactjs react-bootstrap

我正在使用React-Bootstrap,我想获取输入表单的值,以便我可以将它们保存到Firebase。在使用React-Bootstrap之前,我能够使用ref, but now I am not able to do that after using FormGroups`获取输入和文本区域的值。提交表单后,我无法从输入和文本区域中获取值。

我之前看过关于这个问题的帖子,但似乎这些解决方案实际上都没有用。

我是React的新手。有人可以向我解释如何使用Formgroups获取表单值吗?



import React from 'react'
import ReactDOM from 'react-dom'
import {withRouter} from 'react-router'
import './NewListPage.css'
import Header from './Header'
import ListItem from './ListItem'
import database from '../database'
import Form from './Form'
import {
  Button,
  FormGroup,
  FormControl,
  Feedback,
  ControlLabel
} from 'react-bootstrap';

class NewListPage extends React.Component {
  // bring props into constructor
  constructor(props) {
    // bring props into super
    super(props)
    //create list uuid this needs to be A better uuid genereator in the future
    const listId = Math.floor((Math.random() * 10000) + 1)
    this.state = {
      wishList: {
        items: []
      },
      wishListItems: []
    }
    this.addListItem = this.addListItem.bind(this) //bind the add list item function to this component
    this.removeListItem = this.removeListItem.bind(this) //needed to bind update order to root class
    this.saveListItem = this.saveListItem.bind(this) //bind to root class
  }

  addListItem(e) { //add another item to the array
    e.preventDefault()
    // never change state directly, make a copy instead
    const wishList = Object.assign({}, this.state.wishList)
    //push a new item to items object
    wishList.items.push({title: 'title', description: 'description'})
    this.setState({
      //update the state
      wishList
    })
  }

  // remove items from array
  removeListItem(index) {
    // never change state directly, make a copy instead
    const wishList = Object.assign({}, this.state.wishList)
    //remove item object from items array using its index
    wishList.items.splice([index], 1)
    this.setState({
      //update the state from the new array
      wishList
    })
  }

  // save list item into dB
  saveListItem(event) {
    // upon submit, prevent whole page from refreshing
    event.preventDefault()
    // never change state directly, make a copy instead
    const wishList = Object.assign({}, this.state.wishList)
    // grab the title
    wishList.title = this.refs.title.value
    // grab the description
    wishList.description = this.refs.description.value
    // for each item in the list grab its properties
    wishList.items.map((item, index) => {
      // grab descritions and title from generated form
      item.description = this.refs.list.children[index].children.itemdescription.value
      item.title = this.refs.list.children[index].children.itemtitle.value
    })
    // push the wishlist to firebase (need to add code to handle errors.)
    // we use push so that firebase will generate its own uuid
    database.push('wishLists', {
      data: wishList
      // if it saves then resolve this promise and push the uuid to users/uid/wishLists
    }).then(newList => {
      database.push(`users/${this.props.currentUser.uid}/wishLists`, {
        // newList.key contains the firebase uuid from the previous push
        data: newList.key
        // if this also saves then redirect
      }).then(finished => {
        //redirect to dashboard
        this.props.history.push('/')
      })
    })
  }

  render() {
    return (
      <div>
        <h1>Create a New Wishlist</h1>
        <div className="ListForm">
          <Row>
            <Col sm={3}/>
            <Col sm={6}>
              <form onSubmit={this.saveListItem.bind(this)}>
                <FormGroup>
                  <ControlLabel>Wishlist Title</ControlLabel>
                  <br/>
                  <FormControl type="text" name="title"  ref="title" required="true" placeholder="Enter text"/>
                  <FormControl.Feedback/>
                  <br/>
                  <FormGroup controlId="formControlsTextarea">
                    <ControlLabel>Wishlist Description Optional</ControlLabel>
                    <FormControl componentClass="textarea" placeholder="textarea" name="description" ref="description"/>
                  </FormGroup>
                  <br/>

                  <div className="ListItems" ref="list">
                    {this.state.wishList.items.map((item, index) => {
                      return <ListItem removeListItem={this.removeListItem} myIndex={index} key={index}/>
                    })}
                  </div>
                  <Button bsStyle="primary" type="button" onClick={this.addListItem}>ADD ITEM</Button><br/><br/>
                  <input type="submit" value="Save List" ref="save"/>
                </FormGroup>
              </form>
            </Col>
          </Row>
        </div>
      </div>
    )
  }
}
// export with router
export default withRouter(NewListPage)
&#13;
&#13;
&#13;

以下是来自窗口控制台日志的错误消息。

      • enter image description here

1 个答案:

答案 0 :(得分:5)

这是因为您的ref不再是<input> DOM节点,而是React Bootstrap <FormControl>实例。

使用form.elements代替他们name抓住表单的输入:

let form = event.target
wishlist.title = form.elements.title.value
wishlist.description = form.elements.description.value