복붙노트

[REACTJS] 어떻게 확인 체크 박스 값의 배열을 얻을 반응 양식을 사용합니까?

REACTJS

어떻게 확인 체크 박스 값의 배열을 얻을 반응 양식을 사용합니까?

해결법


  1. 1.당신은 순서에 대해 걱정하지 않는다 당신은 단지 그들이 우리가 확실히 정확하게 귀하의 질문에 제안 무엇을 할 수있는 표시로 배열에 항목을 추가하십시오. (체크 또는 체크되지 않은 경우는 false 경우 event.target.checked true를 반환)하고 그에 따라 배열 로직을 처리하는 확인란을 선택하거나 또는 선택하지 않은 경우 체크 박스에 체크의 변경 이벤트에. 이 문제가 해결 수있는 방법의 간단한 표현이다 :

    당신은 순서에 대해 걱정하지 않는다 당신은 단지 그들이 우리가 확실히 정확하게 귀하의 질문에 제안 무엇을 할 수있는 표시로 배열에 항목을 추가하십시오. (체크 또는 체크되지 않은 경우는 false 경우 event.target.checked true를 반환)하고 그에 따라 배열 로직을 처리하는 확인란을 선택하거나 또는 선택하지 않은 경우 체크 박스에 체크의 변경 이벤트에. 이 문제가 해결 수있는 방법의 간단한 표현이다 :

    import React, { Component } from 'react'
    import { connect } from 'react-redux'
    
    class Portfolio extends Component {
      constructor() {
        super()
        // initialize your options array on your state
        this.state = {
          options: []
        }
      }
    
      onChange(e) {
        // current array of options
        const options = this.state.options
        let index
    
        // check if the check box is checked or unchecked
        if (e.target.checked) {
          // add the numerical value of the checkbox to options array
          options.push(+e.target.value)
        } else {
          // or remove the value from the unchecked checkbox from the array
          index = options.indexOf(+e.target.value)
          options.splice(index, 1)
        }
    
        // update the state with the new array of options
        this.setState({ options: options })
      }
    
      render() {
        return (
          <main className='portfolio'>
    
            <form>
              <div className="input-group">
                <label>cb1</label>
                <input type="checkbox" value={1} onChange={this.onChange.bind(this)} />
              </div>
              <div className="input-group">
                <label>cb2</label>
                <input type="checkbox" value={2} onChange={this.onChange.bind(this)} />
              </div>
              <div className="input-group">
                <label>cb3</label>
                <input type="checkbox" value={3} onChange={this.onChange.bind(this)} />
              </div>
            </form>
    
            <div className="selected-items">
              {this.state.options.map(number => 
                 <p key={number}>item: {number}</p>
              )}
            </div>
    
          </main>
        )
      }
    }
    

    내가이 예에서 쉽게 체크 박스가 숫자 값을 분류 줄 수 않았다처럼 배열에 숫자 값을 추가 할 수 있습니다 당신이 상관없이이 특정 순서로 항상 귀하의 상태를 업데이트하기 전에 배열을 정렬 할 수 있다면 당신은 순서에 대해주의 경우 순서는 그들이 확인됩니다.

      onChange(e) {
        // current array of options
        const options = this.state.options
        let index
    
        // check if the check box is checked or unchecked
        if (e.target.checked) {
          // add the numerical value of the checkbox to options array
          options.push(+e.target.value)
        } else {
          // or remove the value from the unchecked checkbox from the array
          index = options.indexOf(+e.target.value)
          options.splice(index, 1)
        }
    
        // sort the array
        options.sort()    
    
        // update the state with the new array of options
        this.setState({ options: options })
      }
    

  2. 2.여기에 내가 그것을하고있어 방법은 다음과 같습니다

    여기에 내가 그것을하고있어 방법은 다음과 같습니다

    // util.js
    import getPath from 'lodash/get';
    import setIn from 'lodash/fp/set';
    
    export function linkMultiCheck(name, value) {
        return {
            checked: getPath(this.state, name, []).includes(value),
            onChange: ev => {
                let values = getPath(this.state, name, []);
                if(ev.target.checked) {
                    values = [...values, value];
                } else {
                    values = values.filter(v => v !== value);
                }
                this.setState(setIn(name, values));
            },
        }
    }
    
    // form.js
    <ul>
        {options.branches.map(branch => (
            <li key={branch.id} className="checkbox">
                <label>
                    <input type="checkbox" name={this.id} {...this::linkMultiCheck('formData.branchIds',branch.id)}/>
                    {branch.id}
                </label>
            </li>
        ))}
    </ul>
    

    체크 박스가 체크되어있는 경우, 즉, 전류 값의 배열에 추가. 이 체크되지 않은 있다면, 그것을 필터링.

    나는 우리가 점 표기법을 사용하여 중첩 상태 값을 설정할 수 있도록 여기 lodash을 사용하고 있습니다.

  3. from https://stackoverflow.com/questions/37129437/how-do-i-use-react-and-forms-to-get-an-array-of-checked-checkbox-values by cc-by-sa and MIT license