在React中如何根据对象值勾选输入复选框

时间:2021-12-25 19:37:25

The check box function works fine and updating selected input value in to this.state = { answers: [] }; At the same time the checkboxes doesn't show as selected on page load when page loading with

复选框功能正常工作,并将选定的输入值更新为this.state = {answers:[]};同时,当页面加载时,复选框在页面加载时不会显示为选中状态

this.state = { 
  answers: [
    {
      questionID: 4, 
      answerValues: ["1", "2", "3", "4"]
    }
  ] 
}

Demo: https://codesandbox.io/s/7jlq387686

{options.map(option => {
  var tick = checked.answerValues.find(answer => answer == option.id );
  return (
    <div className="form-check" key={option.id}>
      <label className="radio-inline" htmlFor={`${name}-${option.id}`}>
        <input
          name={name}
          id={`${name}-${option.id}`}
          type="checkbox"
          value={option.id}
          onChange={e => this.handleChange(e, option.id)}
          checked={option.id == tick}
        />{" "}
        {option.value}
      </label>
    </div>
  );
})}

There are two issues in the current snippet 1) When select from checkbox it works but the preselected items are becoming unselected 2) when page load the checkbox doesn't work it says Cannot read property 'find' of undefined

当前片段中有两个问题1)当从复选框中选择时它可以工作,但是预选的项目将被取消选择2)当页面加载时,复选框不起作用它说无法读取未定义的属性'find'

1 个解决方案

#1


3  

Problem 1

You miss to initialize the selected attribute corresponding with the checked prop:

您错过了初始化与选中的prop相对应的所选属性:

constructor(props, context) {
   super(props, context);

   this.selected = this.answerValues
     .reduce((obj, curr) => ({ ...obj, [curr]: true }), {});

   this.handleChange = this.handleChange.bind(this);
 }

Also add this getter to avoid errors when is not defined:

还要添加此getter以避免在未定义时出错:

 get answerValues() {
   const { answerValues = [] } = this.props.checked || {};
   return answerValues;
 }

Note: Also you can use directly defaultProps to avoid this.

注意:您也可以直接使用defaultProps来避免这种情况。

Problem 2

Instead of this line on render:

而不是渲染上的这一行:

var tick = checked.answerValues.find(answer => answer == option.id);

Use:

var tick = this.answerValues.find(answer => answer == option.id);

Clarifications

  1. On the handleChange from InputCheckbox you were saving the new answerValues as Object.keys(this.selected), and at the beginning this selected was an empty object, this mean, that you was losing the first state. To keep the first state, you need to initialize the selected attribute.
  2. 在InputCheckbox的handleChange中,您将新的answerValues保存为Object.keys(this.selected),并且在开始时,此选择是一个空对象,这意味着您正在丢失第一个状态。要保持第一个状态,您需要初始化所选属性。

  3. Find of undefined was because there isn't an answers array yet, you can't fix this using the getter that I proposed, or also using defaultProps setting to a default value when this array is undefined.
  4. 找到undefined是因为还没有一个答案数组,你不能使用我提出的getter修复它,或者在未定义此数组时使用defaultProps设置为默认值。

Sandbox: https://codesandbox.io/s/wnv238j1ww

#1


3  

Problem 1

You miss to initialize the selected attribute corresponding with the checked prop:

您错过了初始化与选中的prop相对应的所选属性:

constructor(props, context) {
   super(props, context);

   this.selected = this.answerValues
     .reduce((obj, curr) => ({ ...obj, [curr]: true }), {});

   this.handleChange = this.handleChange.bind(this);
 }

Also add this getter to avoid errors when is not defined:

还要添加此getter以避免在未定义时出错:

 get answerValues() {
   const { answerValues = [] } = this.props.checked || {};
   return answerValues;
 }

Note: Also you can use directly defaultProps to avoid this.

注意:您也可以直接使用defaultProps来避免这种情况。

Problem 2

Instead of this line on render:

而不是渲染上的这一行:

var tick = checked.answerValues.find(answer => answer == option.id);

Use:

var tick = this.answerValues.find(answer => answer == option.id);

Clarifications

  1. On the handleChange from InputCheckbox you were saving the new answerValues as Object.keys(this.selected), and at the beginning this selected was an empty object, this mean, that you was losing the first state. To keep the first state, you need to initialize the selected attribute.
  2. 在InputCheckbox的handleChange中,您将新的answerValues保存为Object.keys(this.selected),并且在开始时,此选择是一个空对象,这意味着您正在丢失第一个状态。要保持第一个状态,您需要初始化所选属性。

  3. Find of undefined was because there isn't an answers array yet, you can't fix this using the getter that I proposed, or also using defaultProps setting to a default value when this array is undefined.
  4. 找到undefined是因为还没有一个答案数组,你不能使用我提出的getter修复它,或者在未定义此数组时使用defaultProps设置为默认值。

Sandbox: https://codesandbox.io/s/wnv238j1ww