如何在React中获取当前的onChange值?

时间:2018-08-21 10:04:45

标签: javascript reactjs

我已经帮助了您达到目标,并且我还需要更多帮助。某种意义上,第一次单击除了注册一个空数组外,什么都没有注册。我正在使用handleChange方法查看控制台记录器的结果。该代码可很好地用于返回和更改选择,但由于当前我只能看到结果中的41个元素,因此无法验证表单。请帮我在这里。谢谢。

点击4次后(0: 0, 1: 1, 2: 2, 3: 0)

click1 > []
click2 > {"0":0}
click3 > {"0":0,"1":1}
click4 > {"0":0,"1":1,"2":2}

如何获取元素被点击的值以及其他值?

import React from 'react'

export default class Acme extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      selections: [],
      statements: /*  Array of 42 strings */
    }
    this.handleChange = this.handleChange.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
  }

  handleChange(event) {
    const [id, value] = event.target.value.split('-')
    this.setState({
      selections: {
          ...this.state.selections,
          [id]: parseInt(value, 10)
      }
    })
    console.log(JSON.stringify(this.state.selections))
  }

  handleSubmit(event) {
    event.preventDefault()
    alert('not yet')
  }

  render() {
    return (
      <div>
        <h2>Acme</h2>
        <hr />
        <h3>  instructions...  </h3>

        <form onSubmit={this.handleSubmit}>
          {
            this.state.statements.map(
              (statement, index) => (

                 <h4> {index+1}. &nbsp; {statement} </h4>

                  <input type="radio" value={`${index}-0`}
                      key={`${index}-0`} id={`${index}-0`}
                      checked={this.state.selections[index] === 0 }
                      onChange={this.handleChange} />
                  <label htmlFor={`${index}-0`}>  0 </label>

                  <input type="radio" value={`${index}-1`}
                      key={`${index}-1`} id={`${index}-1`}
                      checked={this.state.selections[index] === 1}
                      onChange={this.handleChange } />
                  <label htmlFor={`${index}-1`}>  1 </label>

                  <input type="radio" value={`${index}-2`}
                      key={`${index}-2`} id={`${index}-2`}
                      checked={this.state.selections[index] === 2 }
                      onChange={this.handleChange } />
                  <label htmlFor={`${index}-2`}>  2 </label>

                  <input type="radio" value={`${index}-3`}
                      key={`${index}-3`} id={`${index}-3`}
                      checked={this.state.selections[index] === 3 }
                      onChange={this.handleChange } />
                  <label htmlFor={`${index}-3`}>  3 </label>
              )
            )
          }
          <button type="submit"> See Results </button>
        </form>
      </div>
    )
  }
}

0 个答案:

没有答案