Javascript 单击按钮时要在saveInfo()函数内执行disNone()函数
单击按钮时,我想在Javascript 单击按钮时要在saveInfo()函数内执行disNone()函数,javascript,reactjs,react-native,ecmascript-6,react-redux,Javascript,Reactjs,React Native,Ecmascript 6,React Redux,单击按钮时,我想在saveInfo()内部执行disNone(): 错误:TypeError:无法读取未定义的属性“disNone” import React, { Component } from 'react'; class Login extends Component { constructor(props){ super(props); this.state = { dispNone:"dispNone", message:"disp
saveInfo()
内部执行disNone()
:
错误:TypeError:无法读取未定义的属性“disNone”
import React, { Component } from 'react';
class Login extends Component {
constructor(props){
super(props);
this.state = {
dispNone:"dispNone",
message:"dispNone"
};
this.disNone = this.disNone.bind(this);
};
disNone(){
this.setState({
dispNone: "dispNone",
message:"dispBlock"
});
}
saveInfo(){
this.disNone();
}
render() {
return (
<div>
// other code
<button onClick={this.saveInfo}>Sign up</button>
</div>
);
}
}
export default Login;
import React,{Component}来自'React';
类登录扩展组件{
建造师(道具){
超级(道具);
此.state={
disponne:“disponne”,
信息:“dispne”
};
this.disNone=this.disNone.bind(this);
};
disNone(){
这是我的国家({
disponne:“disponne”,
消息:“dispBlock”
});
}
saveInfo(){
这个。disNone();
}
render(){
返回(
//其他代码
注册
);
}
}
导出默认登录;
在构造函数中,除了this.disNone=this.disNone.bind(this)
,还需要
this.saveInfo = this.saveInfo.bind(this);
该错误是因为safeInfo
不知道这是什么意思,这会导致disNone未定义的错误
EDIT:我们在构造函数中执行此操作,因为我们只需要将函数绑定一次。或者,您也可以在render
函数中编写它,但这意味着每次执行render
函数时,都会重新绑定该函数,这是一种浪费
第三种选择是在渲染函数中使用()=>this.saveInfo()
,这在任何地方都不需要任何类型的绑定,但同样,每次运行渲染
函数时都必须“创建”此函数。添加
this.saveInfo=this.saveInfo.bind(this)
在构造函数中。
SaveInfo方法无法访问此项。错误是什么?TypeError:无法读取undefinedworks perfect的属性'disNone',谢谢您能解释一下为什么使用this.disNone=this.disNone.bind(this);this.saveInfo=this.saveInfo.bind(this);在constructor function?中添加了一些详细信息,这里还有一篇很好的文章,总结了不同的方法: