You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Stencil.js计数按钮不刷新页面问题求助

Stencil.js计数按钮不刷新&NaN问题解决

问题原因

直接将this.contar绑定到按钮的onClick时,函数内部的this指向触发事件的按钮元素,而非组件实例。这会导致:

  • this.contador并非组件的@State变量,初始为undefined,执行++后变成NaN
  • 组件状态未被正确更新,页面自然不会刷新

解决方案(三种任选其一)

方案1:用箭头函数包裹事件回调

修改按钮的onClick绑定,通过箭头函数确保this指向组件实例:

<button onClick={() => this.contar()}> <span class="menu-icon">CONTAR</span></button>

方案2:在构造函数中绑定this

在组件构造函数里手动绑定contar方法的this:

import { Component, h, State } from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true,
})
export class MyComponent {
  @State() contador = 0;

  constructor() {
    super();
    // 绑定this到组件实例
    this.contar = this.contar.bind(this);
  }

  contar(){
      this.contador++
      console.log(this.contador);
    }

  render() {
    return (
      <div>
        <button onClick={this.contar}> <span class="menu-icon">CONTAR</span></button>
          <nav class="navigation">
            <ul>
              <li><a href="#" class="logo">{this.contador}</a></li>
            </ul>
          </nav>
      </div>
    );
  }
}

方案3:将方法定义为箭头函数

直接把contar定义为箭头函数,自动绑定组件实例的this:

import { Component, h, State } from '@stencil/core';

@Component({
  tag: 'my-component',
  styleUrl: 'my-component.css',
  shadow: true,
})
export class MyComponent {
  @State() contador = 0;

  // 箭头函数自动绑定this
  contar = () => {
      this.contador++
      console.log(this.contador);
    }

  render() {
    return (
      <div>
        <button onClick={this.contar}> <span class="menu-icon">CONTAR</span></button>
          <nav class="navigation">
            <ul>
              <li><a href="#" class="logo">{this.contador}</a></li>
            </ul>
          </nav>
      </div>
    );
  }
}

验证效果

修改后点击按钮,console.log会输出正确的递增数值,页面上的contador也会同步更新,不会再出现NaN或不刷新的问题。

内容的提问来源于stack exchange,提问作者Mr Usher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 00:13:12