我有一个简单的 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;
}
或者你可以在类的构造函数中将handleChange
的this
绑定(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/