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

React表单开发报Cannot read property 'userNameInput' of undefined错误求解

报错触发原因

你遇到的报错由两个问题共同导致:

  1. 类组件事件处理函数this指向丢失:直接将handleSubmit作为onSubmit回调传递时,函数内部的this不会自动绑定到Form组件实例,提交触发时this值为undefined,因此访问this.userNameInput时抛出对应错误。
  2. ref创建方式不符合规范:当前userNameInput被赋值为普通空对象,不是React官方要求的ref实例,即便修复this指向也无法正常获取输入框DOM。

修复方案

仅需要修改Form.js文件即可,参考代码如下:

import React from 'react';

class Form extends React.Component {
  // 用React.createRef创建合法的ref实例
  userNameInput = React.createRef();

  // 用箭头函数定义事件处理方法,自动绑定this到当前组件实例
  handleSubmit = (event) => {
    event.preventDefault();
    console.log(this.userNameInput.current.value);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          placeholder="Github Username"
          ref={this.userNameInput}
          required
        />
        <button>Add Card</button>
      </form>
    );
  }
}

export default Form;

如果你不习惯用箭头函数定义类方法,也可以在构造函数中手动绑定this:

import React from 'react';

class Form extends React.Component {
  constructor(props) {
    super(props);
    this.userNameInput = React.createRef();
    // 手动绑定this指向
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(event) {
    event.preventDefault();
    console.log(this.userNameInput.current.value);
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type="text"
          placeholder="Github Username"
          ref={this.userNameInput}
          required
        />
        <button>Add Card</button>
      </form>
    );
  }
}

export default Form;

同类问题规避要点

  • React类组件传递事件回调时,必须确保回调内部this指向正确,优先使用类字段箭头函数写法,省去手动绑定的冗余步骤
  • 类组件要获取DOM元素时,必须通过React.createRef()创建ref实例,禁止直接赋值普通对象作为ref使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 01:51:01