提问人:Stiven Medina 提问时间:6/16/2023 最后编辑:Stiven Medina 更新时间:6/16/2023 访问量:205
React 同一组件的多个实例都得到相同的回调
React multiple instances of same component are getting the same callback
问:
我有一个 React 组件,它只执行第一个 Component 实例的第一个回调,即使我单击第二个或第三个组件。这是我的代码:
import React, { useState } from 'react';
import styles from './checkbox.module.css';
interface CheckboxProps {
initialState: boolean;
onToggle: () => void;
}
const Checkbox: React.FC<CheckboxProps> = ({ initialState, onToggle }) => {
const [checked, setChecked] = useState<boolean>(initialState);
const handleChange = () => {
const newChecked = !checked;
setChecked(newChecked);
onToggle();
};
return (
<>
<input
className={styles.switch}
type="checkbox"
id="switch"
checked={checked}
onChange={handleChange}
/>
<label className={styles['switch-label']} htmlFor="switch">Toggle</label>
</>
);
};
export default Checkbox;
CSS代码:
.switch {
height: 0;
width: 0;
visibility: hidden;
}
.switch-label {
cursor: pointer;
text-indent: -9999px;
width: 51.2px;
height: 25.6px;
background: rgb(241, 44, 44);
display: block;
border-radius: 80px;
position: relative;
}
.switch-label:after {
content: "";
position: absolute;
top: 4px;
left: 4px;
width: 17.6px;
height: 17.6px;
background: #fff;
border-radius: 70.4px;
transition: 0.3s;
}
.switch:checked + .switch-label {
background: #a5ce1e;
}
.switch:checked + .switch-label:after {
left: calc(100% - 4px);
transform: translateX(-100%);
}
.switch-label:active:after {
width: 22.4px;
}
如果我像这样使用我的组件,即使我点击第二个或第三个组件,React 也只执行第一个组件的回调
<div>
<Checkbox key={1} initialState={false} onToggle={()=>{console.log("One")}} />
<Checkbox key={2} initialState={false} onToggle={()=>{console.log("Two")}} />
<Checkbox key={3} initialState={false} onToggle={()=>{console.log("Three")}} />
</div>
答:
0赞
Ryu
6/16/2023
#1
id 属性在 HTML 文档中是唯一的,因此具有相同 ID 的多个元素可能会导致冲突。
<Checkbox key={1} initialState={false} onToggle={()=>{console.log("One")}} id={'one'}/>
<Checkbox key={2} initialState={false} onToggle={()=>{console.log("Two")}} id={'two'}/>
<Checkbox key={3} initialState={false} onToggle={()=>{console.log("Three")}} id={'three'}/>
请改用它对所有输入进行硬编码“切换”
<>
<input
type="checkbox"
id={id}
checked={checked}
onChange={handleChange}
/>
<label htmlFor={id}>Toggle</label>
</>
评论
0赞
Stiven Medina
6/16/2023
非常感谢您的帮助和提供解决方案!🙏 在仔细查看代码并讨论问题后,很明显,该错误是由对组件中的多个复选框使用相同的属性引起的。id
评论