programing

React에서 확인란 속성 설정

luckcodes 2023. 2. 11. 23:46

React에서 확인란 속성 설정

리액트와 체크박스에 매우 귀찮은 문제가 있습니다.작업 중인 응용 프로그램에는 백엔드로 유지되는 설정을 나타내는 확인란 목록이 필요합니다.설정을 원래 상태로 복원할 수 있는 옵션이 있습니다.

처음에 설정 지도와 같은 오브젝트를 가진 컴포넌트를 만들었습니다.각 설정에는 키와 부울 값이 있습니다.이 때문에,

{
    bubbles: true,
    gregory: false
}

다음과 같이 표현해야 합니다.

<input type="checkbox" value="bubbles" checked="checked" />
<input type="checkbox" value="gregory" />

리액트는 체크박스가 어떻게 작동하는지 모르는 것 같습니다.확인란의 값을 설정하지 않고 "체크된" 속성을 원합니다.

하지만 이런 걸 시도하면

<input
    type="checkbox"
    value={setting}
    checked={this.settings[setting]}
    onChange={this.onChangeAction.bind(this)}
/>

경고는 다음과 같습니다.

경고:AwesomeComponent가 제어할 수 없는 유형의 입력 확인란을 변경하고 있습니다.입력 요소는 제어되지 않음에서 제어됨으로 전환되지 않아야 합니다(또는 그 반대).컴포넌트의 라이프 타임 동안 제어된 입력 요소를 사용할지 또는 제어되지 않은 입력 요소를 사용할지 결정합니다.상세 정보 : [몇 번 읽어도 소용없는 문서 페이지]

그래서 각 체크박스를 랩할 다른 컴포넌트를 작성하기로 결정했고, 다음과 같은 결과가 나왔습니다.

<input
    type="checkbox"
    checked={this.state.checked}
    onChange={this.onChangeAction.bind(this)}
/>

, 이제 ㅇㅇ, ㅇㅇ.checked아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아아.

같은 경고가 하므로, 저는 '이러한 '를 사용해 보겠습니다.defaultChecked:

<input
    type="checkbox"
    defaultChecked={this.state.checked}
    onChange={this.onChangeAction.bind(this)}
/>

로 인해 사라지지만, 수 없습니다.checked디폴트 값으로 설정합니다. 저는 이 놀았습니다.componentWillReceiveProps 내 것이 this.state.checked이 올바르고 컴포넌트가 다시 렌더링됩니다.

그리고 그것은 그렇다.그러나 체크박스는 원래대로 유지됩니다.지금은 그 추악한 경고를 남기고checked고를없 없애 ?떻 떻?? ???

컴포넌트를 수이 있지 새로운 컴포넌트를 .defaultChecked값을 매겨 사용합니다.근데 어떻게 해야 될지 모르겠어요.이 컴포넌트에 대해서만 경고를 억제할 수 있습니까?그게 가능한가요?혹시 다른 방법이 있을까요?

「」를 설정하면, 문제가 합니다.checked을 [ property박스 property property 。null ★★★★★★★★★★★★★★★★★」undefined.

JS의 "falsy" 값입니다.그러나 React는 값이 전혀 설정되지 않은 것으로 간주합니다.기본 확인란이 선택 해제되어 있기 때문에 모든 것이 정상적으로 작동합니다.그 후,checked로.true리액트는 그 부동산이 갑자기 존재한다고 생각한다.이제 React는 당신이 통제되지 않은 상태에서 통제된 상태로 전환한 것을 알 수 있습니다.checked존재한다.

이 예에서는 이 경고를 다음과 같이 변경하여 제거할 수 있습니다.checked={this.settings[setting]}로.checked={!!this.settings[setting]}더블 뱅에 주의해 주세요.!!) 변환됩니다.null또는undefined로.false(떠나세요)true(단독)그래서 React는 다음 주소를 등록합니다.checked가치가 있는 재산false폼 컴포넌트를 제어하고 시작합니다.

저도 이 문제가 있어서 컨트롤 컴포넌트에 대한 문서를 몇 번 읽었지만 소용이 없었습니다만, 드디어 알게 되어 공유하려고 생각하고 있습니다.또한 버전 15.2.0 이후 일반 입력은 다음 설정에 의해 제어됩니다.value체크박스는 설정에 의해 제어된 상태로 초기화됩니다.checked그 어느 쪽이든value그 때문에 혼란이 가중되었습니다.

Amoebe의 답변은 맞지만 더블뱅크보다 더 깨끗한 해결책이 있다고 생각합니다.!!default Props 속성을 value와 함께 추가하기만 하면 됩니다.false위해서checkedCheckbox 컴포넌트의 프로펠러:

import React from 'react';

const Checkbox = ({checked}) => (
  <div>
      <input type="checkbox" checked={checked} />
  </div>
);

Checkbox.defaultProps = {
  checked: false
};

export default Checkbox;

기본적으로는defaultChecked 것을 이 뿐 .이 값을 사용하여 렌더링할 뿐, 제어할 수 있는 방법은 없습니다.ㅇㅇㅇㅇ.value안 되지만,하시면 안 됩니다.checked두 번째 코드가 정확해야 합니다.그리고 두 가지를 동시에 사용해서는 안 됩니다.

<input
    type="checkbox"
    checked={this.state.checked}
    onChange={this.onChangeAction.bind(this)}
/>

당신은 이 행동을 가지고 작은 장난을 칠 수 있습니까?

클래스 컴포넌트를 기능 컴포넌트로 변환하는 경우 후크를 사용한 답변입니다.

export default Checklist = () => {
  const [listOfItems, setListOfItems] = useState([
    {name: 'bubbles', isChecked: true},
    {name: 'gregory', isChecked: false}
  ]);

  const updateListOfItems = (itemIndex, isChecked) => {
    const updatedListOfItems = [...listOfItems];
    updatedListOfItems[itemIndex].isChecked = isChecked;
    setListOfItems(updatedListOfItems);
  }

  return (
    {listOfitems.map((item, index) =>
      <index key={index} type="checkbox" checked={item.isChecked} onChange={() => updateListOfItems(index, !item.isChecked)} />
    )}
  )
}

데이터를 상태에 할당한 다음 개별 확인란과 관련된 선택된 속성을 사용하여 상태를 다음과 같이 설정할 수 있습니다.

{   this.state.data.map(function(item, index) {
      return (
        
        <input type="checkbox" checked={item.value} onChange={this.handleChange.bind(this, index)}/>
        
      );
    }.bind(this))
    }

상태의 샘플 데이터는 다음과 같습니다.

data: [{name:'bubbles', value: true}, {name:'gregory', value: false}]

JSFIDLE

다른 해답을 조합하여 최종적으로 효과가 있는 것:

const [categories, setCategories] = useState(
    [
        {
            field: 'Label 1',
            checked: true
        },
        {
            field: 'Label 2',
            checked: false
        },
        {
            field: 'Label 3',
            checked: false
        }
    ]
)
const updateList = (item, isChecked) => {
    const updatedList = [...categories];
    updatedList[item].checked = isChecked;
    setCategories(updatedList);
}
... in your markup:
{
  categories.map((item, index) =>
    <div key = {item.field}>
      <label>
        <span>{item.field}</span>
        <input key={index}
               type="checkbox"
               checked={item.checked}
               onChange={() => updateList(index, !item.checked)}
         />
      </label>
    </div>
  )
}

언급URL : https://stackoverflow.com/questions/39120007/setting-a-checkbox-check-property-in-react