javascript - ReactJS - 类型错误 : Cannot set property 'propOne' of undefined

标签 javascript reactjs

我有一个简单的 React 组件:

import React from "react";

export default class Car extends React.Component {
  render() {
    return <h2>I am a {this.props.name}</h2>;
  }
}

然后我将此组件导入到另一个组件中。这个新组件有一个文本框,它的 onChange 事件尝试设置一个属性,该属性作为属性传递给组件一。

import React from "react";
import Car from "./Car";

class Garage extends React.Component {
  constructor(props) {
    super(props);
    this.propOne = "Ford";
    this.state = { value: "initial Value" };
  }

  handleChange(event) {

    this.propOne = event.target.value;
  }
  render() {
    return (
      <>
        <input
          type="text"
          value={this.state.value}
          onChange={this.handleChange}
        />
        <Car name={this.propOne} />
      </>
    );
  }
}

export default Garage;

运行此代码后,我收到 TypeError: Cannot set property 'propOne' of undefined 错误

最佳答案

这是因为您正在创建一个新函数并创建 this 的新实例。将其更改为箭头函数 -

 handleChange = (event) => {

    this.propOne = event.target.value;
  }

或者你可以在类的构造函数中将handleChangethis绑定(bind)到父级的this

constructor(props) {
    super(props);
    this.propOne = "Ford";
    this.state = { value: "initial Value" };

    this.handleChange = this.handleChange.bind(this);
  }

关于javascript - ReactJS - 类型错误 : Cannot set property 'propOne' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59515053/

相关文章:

javascript - setInterval 不适用于数组

javascript - 在递归异步 ajax 调用后执行函数

reactjs - 问题 'state value is changed to undefined when Redux action is called'

javascript - 如何在爱彼迎 react 日期中选择小时/分钟

javascript - 从数据库获取值并在 React 前端显示的最佳方法

javascript - HTML5 Gallery 删除下载按钮和播放按钮覆盖?

reactjs - 我应该使用 redux-form 存储而不是组件状态和 Redux 自定义存储吗?

javascript - D3 饼图 : Uncaught Type Error - Cannot read property 'pie' of undefined

javascript - 在 native javascript中动态插入框架集内的框架作为第一框架?

javascript - jsx if else 隐藏元素的简写