reactjs - 如何使用状态从对象调用方法
问题描述
我想在按钮单击时调用一个方法。我有一个这样的对象-
const job = {
position: 'cashier',
type: 'hourly',
isAvailable: true,
showDetails() {
const accepting = this.isAvailable ? 'is accepting applications' : "is not currently accepting applications";
console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);
}
};
我正在将作业对象分配给状态
this.state = {
job : null
}
this.setState({
job : job
})
单击按钮时,我必须调用 showDetails 方法
<button className="showDetails" onClick={this.showDetails}></button>
showDetails(){
this.state.job.showDetails()
}
但这不起作用。我在这里做错了什么。如何调用 showDetails 方法?
解决方案
const job = {
position: 'cashier',
type: 'hourly',
isAvailable: true,
showDetails: () => {
const accepting = this.isAvailable ? 'is accepting applications' : "is not currently accepting applications";
console.log(`The ${this.position} position is ${this.type} and ${accepting}.`);
},
};
将您的按钮更改为此
<button className="showDetails" onClick={() => this.showDetails()}></button>
推荐阅读
- csrf - 由于不活动,该页面已过期
- python - 如何使用views.py为django服务器提供完整的htmlapp
- c# - 对以美元符号 ($) 开头的字符串进行数学运算
- microsoft-metro - Power BI 中的导航
- javascript - 在 Asp.Net MVC 站点中嵌入 Vue.js 应用程序
- sql - SQL“IN”子句使用同时包含/排除项目?
- javascript - 如何在页面完全加载之前在 Chrome 中运行警报,但在它开始之后?
- php - 读取 .txt 并输出包含特定字符串的每一行的 PHP 搜索系统
- powershell - 将哈希表中的数组导出为 CSV,而不使用空白行
- python - Python 调试记录器未出现在控制台中