我想知道如何根据我的复选框选择显示或隐藏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>
在Component
类中添加:
1)已检查到状态。我要做的是创建一个CheckBoxModel类,并向其添加我稍后使用的各种属性,例如isChecked,isActive,isHidden等]]
中的CheckBoxModel的数组:class CheckBoxModel { constructor(id, text) { this.id = id; this.text = text; this.isActive = true; this.isVisible = false; } }
2)state
填充此数组。this.state = { checkboxes:[], }
不要忘记用CheckboxModel
3)添加功能以在复选框数组中找到CheckBox
索引:为OnChange事件的函数:getTaskIndexInArrayById(checkBoxId, checkboxes) { for (let index = 0; index < checkboxes.length; index++) { if (checkboxes[index].id === checkBoxId) { return index; } } return -1; // Not Found }
4)添加一个处理CheckBox
添加到您的复选框以捕获已选中/未选中的更改: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)} />
希望对您有帮助。
您正在使用功能组件,因此如果要在其中保持状态,则需要使用useState
挂钩。您应该阅读钩子https://reactjs.org/docs/hooks-state.html。它们非常有用。