Khp*_*alk 39 javascript ecmascript-6 reactjs ecmascript-7
我收到此错误Uncaught TypeError:每当我在AuthorForm的输入框中输入任何内容时,都无法读取未定义的属性'state'.我正在使用React和ES7.
在ManageAuthorPage中的setAuthorState函数的第3行发生错误.即使我在setAuthorState中放置了console.log(this.state.author),它也会停在console.log并调出错误.
无法通过互联网找到其他人的类似问题.
这是ManageAuthorPage代码:
import React, { Component } from 'react';
import AuthorForm from './authorForm';
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
setAuthorState(event) {
let field = event.target.name;
let value = event.target.value;
this.state.author[field] = value;
return this.setState({author: this.state.author});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.setAuthorState}
/>
);
}
}
export default ManageAuthorPage
Run Code Online (Sandbox Code Playgroud)
这是AuthorForm代码:
import React, { Component } from 'react';
class AuthorForm extends Component {
render() {
return (
<form>
<h1>Manage Author</h1>
<label htmlFor="firstName">First Name</label>
<input type="text"
name="firstName"
className="form-control"
placeholder="First Name"
ref="firstName"
onChange={this.props.onChange}
value={this.props.author.firstName}
/>
<br />
<label htmlFor="lastName">Last Name</label>
<input type="text"
name="lastName"
className="form-control"
placeholder="Last Name"
ref="lastName"
onChange={this.props.onChange}
value={this.props.author.lastName}
/>
<input type="submit" value="Save" className="btn btn-default" />
</form>
);
}
}
export default AuthorForm
Run Code Online (Sandbox Code Playgroud)
mad*_*ox2 60
您必须将事件处理程序绑定到正确的context(this):
onChange={this.setAuthorState.bind(this)}
Run Code Online (Sandbox Code Playgroud)
Ale*_* T. 34
你应该设置super()的this方法
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
constructor(props) {
super(props);
this.handleAuthorChange = this.handleAuthorChange.bind(this);
}
handleAuthorChange(event) {
let {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
另一种替代方案基于setAuthorState:
class ManageAuthorPage extends Component {
state = {
author: { id: '', firstName: '', lastName: '' }
};
handleAuthorChange = (event) => {
const {name: fieldName, value} = event.target;
this.setState({
[fieldName]: value
});
};
render() {
return (
<AuthorForm
author={this.state.author}
onChange={this.handleAuthorChange}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65243 次 |
| 最近记录: |