首页 > 解决方案 > 如何使用状态从对象调用方法

问题描述

我想在按钮单击时调用一个方法。我有一个这样的对象-

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 方法?

标签: 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}.`);
  },
};

将您的按钮更改为此

<button className="showDetails" onClick={() => this.showDetails()}></button>

推荐阅读