首页 > 解决方案 > 无法读取未定义的属性“userNameInput”

问题描述

我正在创建一个简单的 React 应用程序,我知道我应该在这种情况下使用状态,但我找到了一个这样的表单示例,我决定尝试一下。现在我不知道为什么这不起作用,我想了解我收到此消息的原因。我进行了很多搜索,所有具有类似错误的案例似乎都很具体。我收到此错误消息:

Error in /~/src/Form.js (14:26)
Cannot read property 'userNameInput' of undefined

这是我的代码:App.js:

import React from 'react';
import './style.css';
import CardList from './CardList';
import Form from './Form';

const testData = [
  {
    name: 'Dan Abramov',
    avatar_url: 'https://avatars0.githubusercontent.com/u/810438?v=4',
    company: '@facebook'
  },
  {
    name: 'Sophie Alpert',
    avatar_url: 'https://avatars2.githubusercontent.com/u/6820?v=4',
    company: 'Humu'
  },
  {
    name: 'Sebastian Markbåge',
    avatar_url: 'https://avatars2.githubusercontent.com/u/63648?v=4',
    company: 'Facebook'
  }
];

class App extends React.Component {
  render() {
    return (
      <div>
        <div className="header">{this.props.title}</div>
        <Form />
        <CardList profiles={testData} />
      </div>
    );
  }
}

export default App;

Card.js:

import React from 'react';

class Card extends React.Component {
  render() {
    const profile = this.props;
    return (
      <div className="github-profile">
        <img src={profile.avatar_url} alt="profile-img" />
        <div className="info">
          <div className="name">{profile.name}</div>
          <div className="company">{profile.company}</div>
        </div>
      </div>
    );
  }
}

export default Card;

CardList.js:

import React from 'react';

import Card from './Card';

const CardList = props => {
  return props.profiles.map(profile => <Card {...profile} />);
};

export default CardList;

表单.js:

import React from 'react';

class Form extends React.Component {
  userNameInput = {};

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

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

export default Form;

index.js:

import React from 'react';
import ReactDOM from 'react-dom';

import App from './App';

ReactDOM.render(
  <App title="Github Cards App" />,
  document.getElementById('root')
);

您能否解释一下为什么会出现这种错误,以便我下次更好地了解如何处理?

标签: javascriptreactjsecmascript-6

解决方案


您必须绑定 handleSubmit 函数。通过在 Form 组件顶部编写以下代码来做到这一点:

handleSubmit = this.handleSubmit.bind(this);

您可以阅读本文以了解为什么需要绑定函数: 为什么需要在构造函数中绑定函数

重现错误时,我还注意到一个警告:

Warning: Unexpected ref object provided for input. Use either a ref-setter function or React.createRef()

您可以通过编写以下内容来解决此问题:

userNameInput = React.createRef();

代替:

userNameInput = {};

推荐阅读