javascript - 无法读取未定义状态的属性
问题描述
我在单击按钮时无法读取未定义的属性“状态”。这是我的工作
constructor(props){
super()
this.state = {
email:"",
guestName:"",
staffName:"",
};
this.onSend = this.onSend.bind()
}
onSend(){
let val = this.state
console.log(val)
}
render(){
return(
<Button variant="contained" color="primary" className={"send"} onClick={this.onSend}>
Send
</Button>)
}
我错过了什么?
解决方案
您的问题是,this
在您的onSend()
函数中不是指类,而是指调用该函数的元素(在您的情况下是Button
元素)。
要解决此问题,您可以将函数更改为如下代码中的箭头函数,或者您可以将this
引用(类)与.bind(this)
(so onClick={this.onSend.bind(this)}
)绑定
constructor(props){
super()
this.state = {
email:"",
guestName:"",
staffName:"",
};
}
onSend = () => {
let val = this.state
console.log(val)
}
render(){
return(
<Button variant="contained" color="primary" className={"send"} onClick={this.onSend}>
Send
</Button>)
}
推荐阅读
- reactjs - 添加搜索以选择 React Bootstrap React JS
- java - Spring Webflux Callable不适用于异步
- windows - TOX 找不到浏览器二进制文件
- powershell - 无法读取文件内容
- php - 在 URL 重写规则中隐藏(删除)文件夹名称不起作用
- android - 我无法在 Android Studio 中执行测试
- python - 如何从熊猫数据框中递归提取值?
- matlab - 如何用matlab函数求解高阶边界条件微分方程
- google-chrome-extension - Chrome 扩展正在存储未定义的值
- python - 从 DataFrame 中获取可用的最新记录