【问题标题】:Grabbing React form field values for submission抓取 React 表单字段值以进行提交
【发布时间】:2018-04-28 00:22:01
【问题描述】:

给定一个 React 表单,如果选择了 other,我无法从选定的单选按钮和文本框中获取值。我应该能够将这些字段传递到 send() 以获取帖子,但不知道如何获取它们。

class CancelSurvey extends React.Component {
constructor (props) {
  super(props)
  this.state = {
    reasons: [],
    reason: {}
  }
  this.processData = this.processData.bind(this)
  this.handleSubmit = this.handleSubmit.bind(this)
  this.otherSelected = this.state.reason === "otheroption";
}

componentDidMount () {
  this.fetchContent(this.processData)
}

/**
 * Fetch reasons
 */

fetchContent (cb) {
  superagent
    .get('/api/user/survey')
    .then(cb)
}

/**
 * Set state after reasons have been fetched
 * @param data
 */

processData (data) {
  this.setState({
    reasons: data.body
  })
}

handleSubmit (e) {
  e.preventDefault()
  let reason = this.state.reason
  if (reason === 'otheroption') {
    reason = this.state.otherreason
  }
  console.log(reason)
  superagent
    .post('/api/user/survey')
    .send({
      optionId: this.state.reason.reason_id,
      optionText: this.state.reason.client_reason,
      otherReasonText: this.state.otherreason
    })
    .then(function (res) {
      console.log('Survey Sent!')
    })
}
  /**
   * render
   */
  render (props) {
    const content = this.props.config.contentStrings
    const reason = this.state.reasons.map((reason, i) => {
      return (
        <div className='fieldset__item' key={i}>
          <label>{reason.client_reason}</label>
          <input type='radio'
            id={reason.reason_id}
            value={reason.client_reason}
            name='reason'
            checked={this.state.reason.reason_id === reason.reason_id}
            onChange={() => this.setState({reason})} />
        </div>
      )
    })

    return (
      <div className='survey'>
        <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
        <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
        <form id='exit-survey' onSubmit={this.handleSubmit}>
          <fieldset className='fieldset'>
            { reason }
            <label>Other reason not included above:</label>
            <input type='radio'
              id='otheroption'
              name='reason'
              value={this.state.reason.otherreason}
              onChange={() => this.setState({reason:{reason_id: 70, client_reason: 'other'}})} />
            <input className='valid'
              type='text'
              id='otheroption'
              name='othertext'
              placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
              onChange={(event) => this.setState({otherreason: event.target.value})} />
          </fieldset>
          <div className='footer-links'>
            <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
          </div>
        </form>
      </div>
    )
  }
}

export default CancelSurvey

【问题讨论】:

  • 当用户单击单选按钮时,您不会更新状态。我提供给您上一个问题here 的代码笔表明您需要使用状态来处理表单值。
  • @Will - 这个问题/问题有点不同。我不需要将表单字段传递给另一个组件,而是需要能够获取值并在send 函数中提交。我已经更新了我的代码,但它没有拉取要传递的值的表单字段。
  • 它是否发送任何值来代替它们?您是否尝试过使用测试值声明它们处于状态?
  • 我发现我为预定义选项发送了不正确的字段值,但不知道如何捕获和发送 other 选项。
  • 就像我之前说的,你需要处理带有状态的值,你被映射的输入是正确的,但是在 { reason }

标签: reactjs superagent


【解决方案1】:

您的变量不正确。我已将它们更新为我认为正确的内容。

handleSubmit (e) {
  e.preventDefault()
  superagent
    .post('/api/user/survey')
    .send({
      optionId: this.state.reason.reason_id,
      optionText: this.state.reason.client_reason,
      otherReasonText: this.state.reason.otherreason
    })
    .then(function (res) {
      console.log('Survey Sent!')
    })
    .catch(function (err) {
      console.log('Survey submission went wrong...')
    })
}
/**
 * render
 */
render (props) {
    const content = this.props.config.contentStrings
    const reason = this.state.reasons.map((reason, i) => {
        return (
            <div className='fieldset__item' key={i}>
                <label>{reason.client_reason}</label>
                <input 
                    type='radio'
                    id={reason.reason_id}
                    name='reason'
                    checked={this.state.reason.reason_id === reason.reason_id}
                    value={reason.client_reason}
                    onChange={() => this.setState({reason})} />
            </div>
        )
    })

    return (
        <div className='survey'>
            <h2 className='heading md'>{content.memberCancel.exitSurvey.heading}</h2>
            <p className='subpara'>{content.memberCancel.exitSurvey.subHeading}</p>
            <form id='exit-survey' onSubmit={this.handleSubmit}>
                <fieldset className='fieldset'>
                    { reason }
                    <label>Other reason not included above:</label>
                    <input type='radio'
                        id='otheroption'
                        name='otheroption'
                        value={this.state.reason.otherreason}
                        checked={this.state.reason.reason_id === 0}
                        onChange={() => this.setState({ reason: {reason_id: 0, client_reason: ""} })} />
                    <input className='valid'
                        type='text'
                        id='othertext'
                        name='othertext'
                        value={this.state.reason.otherreason}
                        placeholder={content.memberCancel.exitSurvey.reasonPlaceholder}
                        onChange={(event) => this.setState({ reason: {reason_id: 0, client_reason: "", otherreason: event.target.value} })} />
                </fieldset>
                <div className='footer-links'>
                    <button className='btn btn--primary btn--lg' onClick={this.handleSubmit}>{content.memberCancel.exitSurvey.button}</button>
                </div>
            </form>
        </div>
    );
}

【讨论】:

  • 我已根据您的建议更新了我的代码,但在选择 other 单选按钮时提交时未定义。
  • The radio input for other, when selected submitted is logged out as undefined.文本输入已注销,但也未发送。
  • 嗯,设置文本输入的值使其无法更改。
  • 感谢您继续提供帮助。随着文本输入值的更新,它从不受控输入变为受控输入Warning: A component is changing an uncontrolled input of type text to be controlled.
  • 很遗憾没有。它仍然没有使用send()otherReasonText: this.state.reason.otherreason 的文本输入
猜你喜欢
  • 1970-01-01
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多