我是反应框架的初学者,所以我的问题对许多人来说可能是基本的 . 但请相信我,我一直坚持这一部分 . 我试图在按钮单击时获取文本框值,并将值作为prop发送给其他函数 . 我能够提取文本框字段的值,但是在click事件中,我收到错误'无法读取属性'未定义的'道具' .
以下是重点: -
-
termchange()用于提取输入文本值 .
-
handleclick用于提取文本框值onclick事件 .
-
oncitychange是一个函数,我将发送textbox的值(oncitychange()函数在不同的组件内) .
先感谢您 .
这是我的代码: -
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;
3 回答
一切都与范围有关 . 你的功能不知道
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}
替换为:这样,函数范围将紧靠React对象