Ant Design表格行内Switch组件onChange失效问题求助
Hey there! I took a look at your code and spotted the exact issue causing your Switch's onChange callback to fail—let's get this sorted out quickly.
The Root Cause
React uses camelCase for all event handler props, but you've written onchange (lowercase 'c') instead of onChange when rendering your Switch component. React doesn't recognize the lowercase version, so it never triggers your callback or logs "I am here".
Step-by-Step Fix
Correct the event prop name
Locate the Switch component in your table row and replaceonchangewithonChange:// ❌ Wrong (lowercase c) <Switch onchange={() => { console.log("I am here"); handleChange(item.id) }} /> // ✅ Correct (camelCase) <Switch onChange={() => { console.log("I am here"); handleChange(item.id) }} />Optimize state synchronization (optional but recommended)
To properly sync the Switch's state with your component's state, pass the current checked value to the Switch and update yourhandleChangefunction to capture the checked state:// Update your handleChange function const handleChange = (id, e) => { console.log("I am here"); // Update the specific item's checked status in state setData(prevData => prevData.map(item => item.id === id ? {...item, checked: e.target.checked} : item ) ); }; // Render Switch with checked state and proper onChange <Switch checked={item.checked} onChange={(e) => handleChange(item.id, e)} />
Why This Works
React relies on standardized camelCase event props (like onClick, onChange) to attach event listeners. Using lowercase onchange is a common typo that breaks this connection—once you fix that, your callback will fire as expected.
内容的提问来源于stack exchange,提问作者Rich

