簡體   English   中英

參數無法訪問 - [ts] 找不到名稱“產品”

[英]Parameter unreachable - [ts] cannot find name 'product'

我試圖將我的參數product添加到我的按鈕組件

我的函數handleIncrement product設置如下:

handleIncrement = product => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });
  };

我的 onClick 事件: onClick={() => this.handleIncrement(product)}

根據我的理解,它應該可以在我的render()訪問,但是 Typescript 給了我“找不到名稱‘產品’”

我仍然處於 React 和 Typescript 的學習階段。 我做錯了什么還是我完全錯了?

這是完整的代碼:

class Counter extends Component {
  state = {
    count: 0,
    tags: ["tag1", "tag2", "tag3"]
  };

  renderTags() {
    if (this.state.tags.length === 0) return <p>No tags!</p>;
    return (
      <ul>
        {this.state.tags.map(tag => (
          <li key={tag}>{tag}</li>
        ))}
      </ul>
    );
  }

  handleIncrement = product => {
    console.log(product);
    this.setState({ count: this.state.count + 1 });
  };

  render() {
    return (
      <div>
        <span className={this.getBadgeClasses()}>{this.formatCount()}</span>
        <button
          onClick={() => this.handleIncrement(product)}
          className="btn btn-secondary btn-sm"
        >
          Increment
        </button>
        {(this.state.tags.length === 0 && "Please create new tag!") ||
          "tags exists"}
        {this.renderTags()}
      </div>
    );
  }

  private getBadgeClasses() {
    let classes = "badge m-2 badge-";
    classes += this.state.count === 0 ? "warning" : "primary";
    return classes;
  }

  formatCount() {
    const { count } = this.state;
    return count === 0 ? "Zero" : count;
  }
}

export default Counter;

在 JS 中,變量可以在全局范圍內、在函數內或在塊內,這取決於它們的聲明方式或位置。

 var globalVar = 1; function example() { var functionVar = 2; if (functionVar) { let blockVar = 3; // let makes a variable "block-scoped" } }

在任何特定范圍內,您都可以訪問在該范圍內定義的變量以及它之上的所有范圍,直到全局范圍(全局變量在任何地方都可見)。

 var globalVar = 1; function example() { // here we also have access to globalVar, since it's in an upper scope var functionVar = 2; if (functionVar) { // here we have access to globalVar and functionVar, since they are both in an upper scope let blockVar = 3; } }

在組件的render方法中,您使用了一個名為product的變量,但沒有在render范圍內(或以上范圍內)的任何地方定義它:

render() {
  return (
    <div>
      {/* ... */}
      <button
        {/* ... */}
        onClick={() => this.handleIncrement(product)}
        {/*                                 ^^^^^^^ not defined anywhere in this scope */}
      >
      {/* ... */}
    </div>
  );
}

這是一個如何打破的例子:

 function render() { console.log(product); } render();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM