javascript - 无法读取未定义的属性“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')
);
您能否解释一下为什么会出现这种错误,以便我下次更好地了解如何处理?
解决方案
您必须绑定 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 = {};
推荐阅读
- sql - 在 VBA MS Access 中运行两个 SQL 查询。第二个记录集依赖于第一个记录集
- ios - Swift - 将自定义视图模式放置在屏幕中央
- docker - 如何删除与 NextCloud Docker Containers 相关的所有内容,以便我可以重新安装?
- asp.net-core - User.IsInRole 在使用基于策略的授权的视图或代码中始终返回 false
- python - 基于克罗内克积的矩阵乘法
- javascript - 使用 Bootstrap 4 在 JavaScript 中滚动后更改导航栏背景和导航链接颜色
- javascript - Firebase 不仅在某些页面上定义
- android - 使用 just_audiio 的问题
- r - 如何从文本文件中读取列作为现有数据框中的新列?
- firebase - 如何修复 Firestore Flutter 依赖项错误?