Roh*_*rni 1 javascript reactjs react-props
我是反应框架的初学者,所以我的问题对许多人来说可能是基本的.但请相信我,我一直坚持这一部分.我试图在按钮单击时获取文本框值并将值作为prop发送给其他函数.我能够提取文本框字段的值但是在click事件上,我收到一个错误'无法读取'undefined'的属性'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;
Run Code Online (Sandbox Code Playgroud)
一切都与范围有关.你的功能不知道是什么this.您可以this根据您的环境在构造函数或其他选项中进行绑定.
将其添加到构造函数中以进行修复:
this.termchange = this.termchange.bind(this);
this.handleclick = this.handleclick.bind(this);
或者阅读https://blog.andrewray.me/react-es6-autobinding-and-createclass/以获取有关正在发生的事情的更详细说明.
我个人使用ES7胖箭头类方法来实现简单性,我认为大多数开发人员正朝着这个方向前进.
| 归档时间: |
|
| 查看次数: |
4243 次 |
| 最近记录: |