参数无法访问 - [ts] 找不到名称'product'



我试图将我的参数product添加到我的按钮组件

我的函数handleIncrement product设置如下:

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

我的点击事件: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();

相关内容

最新更新