在无渲染React中隐藏或显示具有复选框选择的元素

问题描述 投票:0回答:2

我想知道如何根据我的复选框选择显示或隐藏div。我知道有一个与此类似的话题(how to hide or show a div if checkbox is selected in React JS

但是我有一个无渲染的React应用。那么,在没有render()方法的情况下该如何做呢?

到目前为止,我的代码:

复选框:

                        <div number-input id="vacationPercentageSwitch" class="form-group col-lg-2 col-md-4 col-sm-8" style={{ marginLeft: "38px" }}>
                        <div number-input id="vacationPercentageSwitchDiv" class="form-group col-lg-2 col-md-4 col-sm-8" style={{ marginBottom: "10px" }}>
                            <label htmlFor="inputVacationPercentage" className="switch switch-default">
                                <input id="inputVacationPercentage" type="checkbox" />
                                <span><span></span></span>
                            </label>
                        </div>
                    </div>

我想切换的内容:

                        <div number-input id="qualificationYearDropdown" class="form-group col-lg-2 col-md-4 col-sm-8">
                        <label for="qualificationYearOptions"><span class="requiredAsterisk"></span></label>
                        <select id="qualificationYear" class="form-control">
                            <option>1</option>
                            <option>2</option>
                            <option>3</option>
                            <option>4</option>
                        </select>
                    </div>
javascript reactjs
2个回答
0
投票

Component类中添加:

1)已检查状态。我要做的是创建一个CheckBoxModel类,并向其添加我稍后使用的各种属性,例如isCheckedisActiveisHidden等]]

class CheckBoxModel {
  constructor(id, text) {
    this.id = id;
    this.text = text;
    this.isActive = true;
    this.isVisible = false;
  }
}

2)state

中的CheckBoxModel的数组:
this.state = {
   checkboxes:[],
}

不要忘记用CheckboxModel

填充此数组。

3)添加功能以在复选框数组中找到CheckBox

索引:
getTaskIndexInArrayById(checkBoxId, checkboxes) {
   for (let index = 0; index < checkboxes.length; index++) {
      if (checkboxes[index].id === checkBoxId) {
         return index;
      }
   }
   return -1; // Not Found
}

4)添加一个处理CheckBox

OnChange事件的函数:
onCheckBoxChanged(event) {
   checkBoxId = item.currentTarget.id;
   const {attributes } = event.currentTarget;
   let ( checkboxes } = this.state;
   checkboxIndex = this.getCheckBoxIndexById(checkBoxId, checkboxes);
   if (checkboxIndex !== -1) {
      checkboxes[checkboxIndex].isChecked = !checkboxes[checkboxIndex].isChecked;
      if (checkboxes[checkboxIndex].isChecked) {
         // Your code for when checkbox got checked
      } else {
         // Your code for when checkbox got unchecked
      }
      this.setState({ checkboxes });
   }
}

5)将OnChange

添加到您的复选框以捕获已选中/未选中的更改:
<input id="inputVacationPercentage" type="checkbox" onChange={(event) => this.onCheckBoxChanged(event)} />

希望对您有帮助。


0
投票

您正在使用功能组件,因此如果要在其中保持状态,则需要使用useState挂钩。您应该阅读钩子https://reactjs.org/docs/hooks-state.html。它们非常有用。

© www.soinside.com 2019 - 2024. All rights reserved.