【问题标题】:Parameter unreachable - [ts] cannot find name 'product'参数无法访问 - [ts] 找不到名称“产品”
【发布时间】:2019-06-15 04:46:17
【问题描述】:

我正在尝试将我的参数 product 添加到我的按钮组件中

我的函数handleIncrementproduct 设置如下:

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

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

据我了解,它应该可以在我的render() 中访问,但 Typescript 给了我“找不到名称'Product'”

我仍处于 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;

【问题讨论】:

  • 您希望productonClick 中是什么?

标签: javascript reactjs typescript


【解决方案1】:

在 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();

【讨论】:

  • 感谢您的详细回复。我很好奇在过去的 6 个月中这方面是否发生了变化,因为我学习的材料确实在我编写代码时编写它而没有在任何地方定义它,所以我的理解是,如果我像这样使用它,我不必这样做.
猜你喜欢
  • 2018-07-08
  • 2019-07-13
  • 2018-04-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-09
  • 1970-01-01
  • 1970-01-01
  • 2019-12-25
相关资源
最近更新 更多