javascript – 与ES7反应:未捕获TypeError:无法读取未定义的属性’state’

前端之家收集整理的这篇文章主要介绍了javascript – 与ES7反应:未捕获TypeError:无法读取未定义的属性’state’前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这个问题在这里已经有一个答案:> Unable to access React instance (this) inside event handler5个
我收到这个错误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

这里是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

解决方法

您必须将事件处理程序绑定到正确的上下文(这):
onChange={this.setAuthorState.bind(this)}
原文链接:https://www.f2er.com/js/149986.html

猜你在找的JavaScript相关文章