我正在使用Next.jsand開發一個專案Typescript。我有一個表格,這是第一次使用Typescript復選框型別。我在嘗試獲取復選框的所有值時遇到問題,如果為真則添加或如果為假則洗掉。另外,我嘗試了擴展運算子,但它破壞了代碼。這是代碼:
狀態:
const [callTime, setCallTime] = useState<any>('');
const [isChecked, setIsChecked] = useState<boolean>(false);
大批:
const preferredTime = [
{
time: 'Before 9am',
},
{
time: '9am to 12pm',
},
{
time: '12pm to 3pm',
},
{
time: 'After 3pm',
},
];
處理程式:
const onChangeCheckBox = (e: { target: { checked: boolean; value: React.SetStateAction<string>; }; }) => {
setIsChecked(() => e.target.checked);
// setIsChecked(() => !isChecked);
setCallTime(e.target.value)
console.log('radio', e.target.value);
console.log('radio', e.target.checked);
}
回傳:
<p>Preferred call back time</p>
<div className={styles.radioGroup}>
{preferredTime.map((item, index) => (
<div key={index} className={styles.radios}>
<label htmlFor={item.time} className={styles.checkLabel}>{item.time}
<input
type="checkbox"
value={item.time}
name="time"
onChange={onChangeCheckBox}
id={item.time}
// checked={item.checked}
/>
<span className={styles.checkSpan}></span>
</label>
</div>
))}
</div>
這是一個包含完整代碼的Codesanbox :
uj5u.com熱心網友回復:
我想你想做的是:https ://codesandbox.io/s/damp-resonance-e4bnyc?file=/src/App.tsx
我將您的 callTime 狀態中的字串替換為包含的物件陣列,{time: string, isChecked: boolean}
多虧了這一點,您可以輕松管理陣列中每個條目的檢查狀態。所以有了這個,我把checked={item.isChecked}你的 JSX 的地圖
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/482979.html
