gpt4 book ai didi

javascript - React.js onclick事件: Cannot read property 'props' of undefined

转载 作者:行者123 更新时间:2023-12-03 13:58:04 25 4
gpt4 key购买 nike

我是 react 框架的初学者,所以我的问题对你们中的许多人来说可能显得很基本。但相信我,我一直被困在这部分。我试图获取按钮单击时的文本框值并将该值作为 Prop 发送给其他函数。我能够提取文本框字段的值,但在单击事件上,我收到错误“无法读取未定义的属性“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 是什么。您可以在构造函数中绑定(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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com