如何简化 JavaScript/React
How to simplify JavaScript/React
我想简化以下代码:
(如你所见,我有很多document.getElementById
)
clickText() {
document.getElementById("choiceInput").style.display = "none";
document.getElementById("dateInput").style.display = "none";
document.getElementById("textInput").style.display = "block";
document.getElementById('buttonFont').classList.remove('buttonUnselectAfterClick');
document.getElementById('buttonFont').classList.add('buttonSelectAfterClick');
document.getElementById('buttonCalendar').classList.remove('buttonSelectAfterClick');
document.getElementById('buttonCalendar').classList.add('buttonUnselectAfterClick');
document.getElementById('buttonBoolean').classList.remove('buttonSelectAfterClick');
document.getElementById('buttonBoolean').classList.add('buttonUnselectAfterClick');
}
此外,我正在使用 reactjs。
你可以使用Map、Set和for...of循环,通过对它们进行分组来稍微简化代码,而且不需要任何库和框架:
const displayList = new Map([['choiceInput', 'none'], ['dateInput', 'none'], ['textInput', 'block']]);
const eventList = new Set(['buttonFont', 'buttonCalendar', 'buttonBoolean']);
clickText() {
// For display attr
for([key, val] of displayList) {
document.getElementById(key).style.display = val;
}
// For events
for(item of eventList) {
document.getElementById(item).classList.remove('buttonUnselectAfterClick');
document.getElementById(item).classList.add('buttonUnselectAfterClick');
}
}
我想简化以下代码:
(如你所见,我有很多document.getElementById
)
clickText() {
document.getElementById("choiceInput").style.display = "none";
document.getElementById("dateInput").style.display = "none";
document.getElementById("textInput").style.display = "block";
document.getElementById('buttonFont').classList.remove('buttonUnselectAfterClick');
document.getElementById('buttonFont').classList.add('buttonSelectAfterClick');
document.getElementById('buttonCalendar').classList.remove('buttonSelectAfterClick');
document.getElementById('buttonCalendar').classList.add('buttonUnselectAfterClick');
document.getElementById('buttonBoolean').classList.remove('buttonSelectAfterClick');
document.getElementById('buttonBoolean').classList.add('buttonUnselectAfterClick');
}
此外,我正在使用 reactjs。
你可以使用Map、Set和for...of循环,通过对它们进行分组来稍微简化代码,而且不需要任何库和框架:
const displayList = new Map([['choiceInput', 'none'], ['dateInput', 'none'], ['textInput', 'block']]);
const eventList = new Set(['buttonFont', 'buttonCalendar', 'buttonBoolean']);
clickText() {
// For display attr
for([key, val] of displayList) {
document.getElementById(key).style.display = val;
}
// For events
for(item of eventList) {
document.getElementById(item).classList.remove('buttonUnselectAfterClick');
document.getElementById(item).classList.add('buttonUnselectAfterClick');
}
}