代码之家  ›  专栏  ›  技术社区  ›  Rohan Kulkarni

反应js onclick事件:无法读取未定义的属性“props”

  •  4
  • Rohan Kulkarni  · 技术社区  · 7 年前

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

    以下是要点:-

    1. termchange()用于提取输入文本值。
    2. handleclick用于提取单击事件的文本框值。
    3. 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 回复  |  直到 7 年前
        1
  •  8
  •   Travis White    7 年前

    这都是关于范围的。你的功能不知道什么 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类方法,我认为大多数开发人员正在朝着这个方向发展。

        2
  •  2
  •   SALEH    7 年前

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

        3
  •  0
  •   pablopunk    7 年前

    只需更换 onClick={this.handleClick} 签署人:

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

    这样,函数范围将紧密地连接到React对象