React.js onclick 事件:无法读取未定义的 属性 'props'

React.js onclick event: Cannot read property 'props' of undefined

我是 React 框架的初学者,所以我的问题对你们中的许多人来说可能很基础。但请相信我,我一直停留在这部分。 我试图在单击按钮时获取文本框值,并将该值作为道具发送给其他函数。 我能够提取文本框字段的值,但是在单击事件中,我收到错误消息“无法读取未定义的 属性 'props'”。

以下是要点:-

  1. termchange() 用于提取输入文本值。
  2. handleclick 用于提取文本框值的onclick 事件。
  3. oncitychange 是我必须将文本框的值发送到的函数 (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;

在构造函数中添加this.handleClick = this.handleClick.bind(this)

一切都与范围有关。您的函数不知道 this 是什么。您可以在构造函数中绑定 this,或者其他选项可能更容易,具体取决于您的环境。

将此添加到您的构造函数以修复:

this.termchange = this.termchange.bind(this); this.handleclick = this.handleclick.bind(this);

或阅读 https://blog.andrewray.me/react-es6-autobinding-and-createclass/ 以获取有关正在发生的事情的更详细说明。

为了简单起见,我个人使用 ES7 fat arrow class 方法,我认为大多数开发人员都在朝这个方向发展。

只需将 onClick={this.handleClick} 替换为:

onClick={this.handleClick.bind(this)}

这样一来,函数作用域就会限制在 React 对象中