[英]React.js onclick event: Cannot read property 'props' of undefined
我是react框架的初学者,所以我的问题对你们中的许多人来说似乎是基本的。 但请相信我,我一直在这方面停留。 我试图在单击按钮时获取文本框值,并将该值作为道具发送给其他函数。 我能够提取文本框字段的值,但是在click事件上,出现错误“无法读取未定义的属性'props'”。
这里是要点:
先感谢您。
这是我的代码:
import React,{ Component } from 'react';
import ReactDom from 'react-dom';
class SearchBar extends Component {
constructor(props){
super(props);
this.state = {
cityname:''
}
}
render(){
return(
<div>
<span>Enter the city: </span>
<input type="text" id="txtbox" value={this.state.cityname}
onChange={event=>this.termchange(event.target.value)} />
<input type="submit" onClick={this.handleclick} />
</div>
);
}
termchange(cityname){
this.setState({cityname});
}
handleclick(){
this.props.oncitychange(cityname);
}
}
export default SearchBar;
这全都与范围有关。 您的函数不知道this
是什么。 您可以在构造函数中绑定this
,或者根据您的环境,其他选项可能更容易。
将此添加到您的构造函数以修复:
this.termchange = this.termchange.bind(this); this.handleclick = this.handleclick.bind(this);
或阅读https://blog.andrewray.me/react-es6-autobinding-and-createclass/以获取有关发生的情况的更详细说明。
为了简化起见,我个人使用ES7粗箭头类方法,我认为大多数开发人员都朝着这个方向发展。
在构造函数中添加this.handleClick = this.handleClick.bind(this)
只需将onClick={this.handleClick}
替换为:
onClick={this.handleClick.bind(this)}
这样,功能范围将与React对象紧密相关
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.