传递给onclick属性的类函数未定义

时间:2019-08-27 15:09:05

标签: javascript es6-class

我正在尝试构建一个以某种方式模仿React类的构造方式的类。这是我到目前为止的内容:

@TestOn("ios")
import 'package:flutter/cupertino.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/src/app.dart';

void main() {
  group('IOS only Test', () {
    testWidgets('Load IOS App', (WidgetTester tester) async {
    await tester.pumpWidget(App());
    expect(find.byType(CupertinoApp), findsOneWidget);
    });
  });
}

问题是,当我单击链接时,它显示为export default class Pagination { constructor(attr) { const { totalPages } = attr; this.totalPages = totalPages; this.activePage = 1; } goToPage(newPageNumber) { console.log(newPageNumber); } render() { const pages = []; for (let i = 1; i <= this.totalPages; i++) { pages.push(` <li> <a href="javascript:void(0)" onclick="this.goToPage(${i})" class="${ i === this.activePage ? 'active' : '' }">${i}</a> </li> `); } return pages.join(''); } } 。如何正确地将我的类的方法this.goToPage is not a function分配给goToPage标签?

1 个答案:

答案 0 :(得分:2)

您必须将goToPage绑定到父上下文:

constructor(attr) {
   const { totalPages } = attr;

   this.totalPages = totalPages;
   this.activePage = 1;

   this.goToPage = this.goToPage.bind(this);
}

但是,请记住,在html元素中调用onclick会自动将this分配给元素上下文。因此,您需要改为使用eventListenter

相关问题