You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Ant Design表格行内Switch组件onChange失效问题求助

Fixing Unresponsive Switch onChange Callback in Your React Table

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

  1. Correct the event prop name
    Locate the Switch component in your table row and replace onchange with onChange:

    // ❌ 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) }} />
    
  2. 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 your handleChange function 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 22:42:38