我正在使用帶有 Typescript 的 ReactJS,目標是擁有一個復選框組件,根據是否選中復選框向字串陣列添加和洗掉專案。我當前的函式只添加到陣列中,所以當我選擇然后取消選擇一個復選框時,該專案被添加了兩次。提前致謝。
功能:
const handleGroupChange = (groupOptions: any) => {
const existSelection = selectedGroups;
existSelection.push(groupOptions.target.value);
setSelectedGroups(existSelection);
}
};
復選框:
<FormControlLabel
control={
<Checkbox
color="primary"
onChange={e => handleGroupChange(e)}
value={"MATCHED_MENTORS"}
/>
}
uj5u.com熱心網友回復:
檢查是否在 onChange 事件上選中了復選框。
const handleGroupChange = (groupOptions: any) => {
const existSelection = selectedGroups;
if (groupOptions.target.checked) {
existSelection.push(groupOptions.target.value);
} else {
var index = existSelection.indexOf(groupOptions.target.value);
if (index !== -1) {
existSelection.splice(index, 1);
}
}
setSelectedGroups(existSelection);
}
uj5u.com熱心網友回復:
您需要檢查復選框boolean property是否checked存在。請按照下面的示例進行操作,這里是Codesandbox
const [selectedGroups, setSelectedGroups] = useState([]);
const handleGroupChange = (groupOptions) => {
let existSelection = selectedGroups;
if (groupOptions.target.checked)
existSelection.push(groupOptions.target.value);
else
existSelection = existSelection.filter(item => item !== groupOptions.target.value)
console.log(selectedGroups);
setSelectedGroups(existSelection);
uj5u.com熱心網友回復:
這里的問題是您將布林值作為專案推送,因此existSelection陣列應該看起來[true, false, true, false]或多或少。如果這是您想要的行為,那應該是值得一看的。
如果我正確理解你想要的是練習,也許你可以試試這個:
const randomStrings = ['gelato', 'frozen_yogurt', 'ice_cream'];
然后當您單擊復選框時,它將觸發 onChange 將連接到handleGroupChange函式,這將類似于:
const handleGroupChange = (isChecked) = {
if(isChecked){
//We create a random number between 0 and 2
const randomIndex = Math.floor(Math.random() * 2);
//We select an element from randomStrings array based on the random
index generated above
const randomStr = this.randomStrings[randomIndex];
//Looks if the randomStr already exist in existSelection
if nothing found it findIndex returns - 1 wich tell us
this item is not in the array so we push it.
const existInArr = this.existSelection.findIndex(randomStr);
if(existInArr === - 1){
existSelection.push(randomStr);
}
//I guess you also wanna feed a useState hook here.
setExistSelection(randomStr);
}
};
這應該可以解決問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/359513.html
