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

React 18.2中onInput is not a function报错排查求助

解决React 18.2中自定义Input组件onInput is not a function错误

排查步骤及解决方案:

  • 检查props传递是否正确
    确认父组件调用Input时,是否正确传递了onInput函数,注意React事件采用驼峰命名(onInput而非oninput)。比如:

    // 父组件中正确写法
    <Input onInput={handleInputChange} name="username" ... />
    

    同时检查handleInputChange函数是否在父组件中正确定义,比如关联useReducer的dispatch:

    const handleInputChange = (e) => {
      dispatch({
        type: 'INPUT_UPDATE',
        payload: { name: e.target.name, value: e.target.value }
      });
    };
    
  • 在Input组件内校验props
    在Input组件调用onInput的代码前,打印props确认onInput是否存在且为函数:

    console.log('Input props:', props);
    

    如果onInput未定义,说明父组件漏传;如果不是函数,检查父组件传递的是否为函数引用(而非函数调用结果,比如不要写成onInput={handleInputChange()})。

  • 添加函数存在性判断
    React 18对类型校验更严格,调用onInput前先判断是否存在,避免报错:

    // 原错误代码可能是直接调用
    onInput(e);
    // 修改为
    props.onInput?.(e);
    // 或者
    if (typeof props.onInput === 'function') {
      props.onInput(e);
    }
    
  • 排除React StrictMode影响
    React 18的StrictMode会触发两次渲染,可暂时关闭index.js中的StrictMode包裹,验证是否解决问题:

    // 原代码
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <App />
      </React.StrictMode>
    );
    // 修改为
    ReactDOM.createRoot(document.getElementById('root')).render(
      <App />
    );
    

内容的提问来源于stack exchange,提问作者yuroni

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:31:03