作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 react 框架的初学者,所以我的问题对你们中的许多人来说可能显得很基本。但相信我,我一直被困在这部分。我试图获取按钮单击时的文本框值并将该值作为 Prop 发送给其他函数。我能够提取文本框字段的值,但在单击事件上,我收到错误“无法读取未定义的属性“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
是什么。您可以在构造函数中绑定(bind) this
,或者根据您的环境,其他选项可能会更容易。
将其添加到构造函数中进行修复:
this.termchange = this.termchange.bind(this);
this.handleclick = this.handleclick.bind(this);
或阅读https://blog.andrewray.me/react-es6-autobinding-and-createclass/了解正在发生的事情的更详细解释。
为了简单起见,我个人使用 ES7 胖箭头类方法,我认为大多数开发人员都在朝这个方向发展。
关于javascript - React.js onclick事件: Cannot read property 'props' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47560109/
我是一名优秀的程序员,十分优秀!