我正在创建一个简单的 React 应用程序,我知道我应该在这种情况下使用状态,但我发现了一个执行类似表单的示例,我决定尝试一下。现在我不知道为什么这不起作用,我想了解我收到此消息的原因。我搜索了很多,所有具有类似错误的案例似乎都很具体。我收到此错误消息:
Error in /~/src/Form.js (14:26)
Cannot read property 'userNameInput' of undefined
这是我的代码: 应用程序.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;
Form.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')
);
您能否解释一下为什么会出现这种错误,以便我下次更好地处理?
最佳答案
您必须绑定(bind)handleSubmit函数。通过在 Form 组件顶部写入以下内容来完成此操作:
handleSubmit = this.handleSubmit.bind(this);
您可以阅读以下内容来了解为什么需要绑定(bind)该函数: why do you need to bind a function in a constructor
在重现错误时我还注意到一个警告:
Warning: Unexpected ref object provided for input. Use either a ref-setter function or React.createRef()
您可以通过编写以下内容来解决此问题:
userNameInput = React.createRef();
而不是:
userNameInput = {};
关于javascript - 无法读取未定义的属性 'userNameInput',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68686680/