[英]Checkbox form on Next.js and Typescript project
I am working on a projet with Next.js
and Typescript
.我正在使用
Next.js
和Typescript
。 I have a form and it is the first time working with Typescript
and the checkbox type.我有一个表单,这是第一次使用
Typescript
和复选框类型。 I am having issues trying to get all the values of the checkboxes, adding if it is true or deleting if it is false.我在尝试获取复选框的所有值时遇到问题,如果为真则添加或如果为假则删除。 Also, I tried the spread operator but it breaks the code.
另外,我尝试了扩展运算符,但它破坏了代码。 This is the code:
这是代码:
States:状态:
const [callTime, setCallTime] = useState<any>('');
const [isChecked, setIsChecked] = useState<boolean>(false);
Array:大批:
const preferredTime = [
{
time: 'Before 9am',
},
{
time: '9am to 12pm',
},
{
time: '12pm to 3pm',
},
{
time: 'After 3pm',
},
];
Handler:处理程序:
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);
}
return:返回:
<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>
This is a Codesanbox with the whole code:这是一个包含完整代码的Codesanbox :
I think what you wanted to do is this: https://codesandbox.io/s/damp-resonance-e4bnyc?file=/src/App.tsx我想你想做的是: https ://codesandbox.io/s/damp-resonance-e4bnyc?file=/src/App.tsx
I replaced the string in your callTime state by an array of object containing {time: string, isChecked: boolean}
Thanks to this you can easily manage the check status of each entry in the array.我用包含
{time: string, isChecked: boolean}
的对象数组替换了 callTime 状态中的字符串,因此您可以轻松管理数组中每个条目的检查状态。 So with this, I put the checked={item.isChecked}
in the map of your JSX所以有了这个,我把
checked={item.isChecked}
放在你的 JSX 的地图中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.