蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

离线 Chromium 验证合成事件 preventDefault、类方法 this 绑定与箭头/bind 传参

PYTHONWindows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。explore-event-handle.py
explore-event-handle.py258 行
"""Offline Chromium lab for React Ch 16: event-handle."""
import json
from playwright.sync_api import sync_playwright

HTML = """<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><title>React Event Handle Lab</title></head>
<body>
  <div id="link-root"></div>
  <div id="toggle-root"></div>
  <div id="bind-root"></div>
  <div id="args-root"></div>
  <script>
    'use strict';

    // Minimal SyntheticEvent wrapper matching React semantics (returning false does NOT preventDefault)
    function createSyntheticEvent(nativeEvent) {
      return {
        type: nativeEvent.type,
        nativeEvent,
        target: nativeEvent.target,
        get defaultPrevented() { return nativeEvent.defaultPrevented; },
        preventDefault() { nativeEvent.preventDefault(); },
        stopPropagation() { nativeEvent.stopPropagation(); }
      };
    }

    function createElement(type, props, ...children) {
      return { type, props: Object.assign({}, props || {}, { children: children.flat(Infinity) }) };
    }

    function renderVNode(vnode) {
      if (typeof vnode === 'string' || typeof vnode === 'number') return document.createTextNode(String(vnode));
      const el = document.createElement(vnode.type);
      for (const [k, v] of Object.entries(vnode.props)) {
        if (k === 'children' || v === undefined || v === null) continue;
        if (k.startsWith('on') && typeof v === 'function') {
          const domEvent = k.slice(2).toLowerCase();
          el.addEventListener(domEvent, (nativeEvent) => {
            // Note: React ignores handler return value (e.g., return false does NOT prevent default)
            v(createSyntheticEvent(nativeEvent));
          });
        } else {
          el.setAttribute(k === 'className' ? 'class' : k, String(v));
        }
      }
      vnode.props.children.forEach(c => el.appendChild(renderVNode(c)));
      return el;
    }

    class Component {
      constructor(props) { this.props = props; this.state = {}; }
      setState(updater) {
        const next = typeof updater === 'function' ? updater(this.state, this.props) : updater;
        this.state = Object.assign({}, this.state, next);
        this._commit();
      }
      _commit() {
        if (!this._container) return;
        this._container.innerHTML = '';
        this._container.appendChild(renderVNode(this.render()));
      }
      _mount(container) {
        this._container = container;
        this._commit();
      }
    }

    window.runLab = function () {
      // Case 1: camelCase onClick, return false does NOT cancel default, e.preventDefault() DOES
      const linkRoot = document.getElementById('link-root');
      let returnFalseEventType = null;
      let preventDefaultEventType = null;
      const linkA = renderVNode(createElement('a', {
        id: 'link-return-false',
        href: '#ignored',
        onClick: (e) => { returnFalseEventType = e.type; return false; }
      }, 'Return False Link'));
      const linkB = renderVNode(createElement('a', {
        id: 'link-prevent',
        href: '#blocked',
        onClick: (e) => { e.preventDefault(); preventDefaultEventType = e.type; }
      }, 'PreventDefault Link'));
      linkRoot.appendChild(linkA);
      linkRoot.appendChild(linkB);

      const evA = new MouseEvent('click', { bubbles: true, cancelable: true });
      const evB = new MouseEvent('click', { bubbles: true, cancelable: true });
      linkA.dispatchEvent(evA);
      linkB.dispatchEvent(evB);

      const case1 = {
        return_false_prevented_default: evA.defaultPrevented,
        prevent_default_cancelled: evB.defaultPrevented,
        synthetic_event_types: [returnFalseEventType, preventDefaultEventType]
      };

      // Case 2: Toggle class component with constructor .bind(this) + unbound this === undefined check
      class Toggle extends Component {
        constructor(props) {
          super(props);
          this.state = { isToggleOn: true };
          this.handleClick = this.handleClick.bind(this);
        }
        handleClick() {
          this.setState(prevState => ({ isToggleOn: !prevState.isToggleOn }));
        }
        unboundMethod() {
          return typeof this;
        }
        render() {
          return createElement('button', { id: 'toggle-btn', onClick: this.handleClick },
            this.state.isToggleOn ? 'ON' : 'OFF');
        }
      }
      const toggle = new Toggle({});
      toggle._mount(document.getElementById('toggle-root'));
      const states = [document.getElementById('toggle-btn').textContent];
      document.getElementById('toggle-btn').click();
      states.push(document.getElementById('toggle-btn').textContent);
      document.getElementById('toggle-btn').click();
      states.push(document.getElementById('toggle-btn').textContent);
      const detached = toggle.unboundMethod;
      const unboundThisType = detached();

      const case2 = {
        toggle_sequence: states,
        unbound_this_type: unboundThisType
      };

      // Case 3: Class field arrow (stable ref across renders) vs inline arrow (new ref each render)
      class FieldArrowButton extends Component {
        constructor(props) { super(props); this.hits = 0; }
        handleClick = () => { this.hits += 1; return this instanceof FieldArrowButton; };
        render() { return createElement('button', { onClick: this.handleClick }, 'FieldArrow'); }
      }
      class InlineArrowButton extends Component {
        constructor(props) { super(props); this.hits = 0; }
        handleClick() { this.hits += 1; return this instanceof InlineArrowButton; }
        render() { return createElement('button', { onClick: (e) => this.handleClick(e) }, 'InlineArrow'); }
      }
      const fa = new FieldArrowButton({});
      const faRef1 = fa.render().props.onClick;
      const faRef2 = fa.render().props.onClick;
      const ia = new InlineArrowButton({});
      const iaRef1 = ia.render().props.onClick;
      const iaRef2 = ia.render().props.onClick;

      const case3 = {
        field_arrow_this_ok: faRef1(),
        field_arrow_same_ref: faRef1 === faRef2,
        inline_arrow_this_ok: iaRef1(),
        inline_arrow_same_ref: iaRef1 === iaRef2
      };

      // Case 4: Passing arguments via arrow function vs Function.prototype.bind (event e comes last)
      const calls = [];
      class Popper extends Component {
        constructor(props) {
          super(props);
          this.state = { name: 'Hello world!' };
        }
        deleteRow(id, e) {
          calls.push({ method: 'deleteRow', id, eventType: e.type });
        }
        preventPop(name, e) {
          e.preventDefault();
          calls.push({ method: 'preventPop', name, eventType: e.type, prevented: e.defaultPrevented });
        }
        render() {
          return createElement(
            'div', null,
            createElement('button', { id: 'del-arrow', onClick: (e) => this.deleteRow(101, e) }, 'Del Arrow'),
            createElement('button', { id: 'del-bind', onClick: this.deleteRow.bind(this, 202) }, 'Del Bind'),
            createElement('a', {
              id: 'pop-link',
              href: 'https://react.dev',
              onClick: this.preventPop.bind(this, this.state.name)
            }, 'Click')
          );
        }
      }
      const popper = new Popper({});
      popper._mount(document.getElementById('args-root'));
      document.getElementById('del-arrow').click();
      document.getElementById('del-bind').click();
      const popEv = new MouseEvent('click', { bubbles: true, cancelable: true });
      document.getElementById('pop-link').dispatchEvent(popEv);

      const case4 = {
        calls,
        link_default_prevented: popEv.defaultPrevented
      };

      return { case1, case2, case3, case4 };
    };
  </script>
</body>
</html>
"""


def launch_browser(p):
    try:
        return p.chromium.launch(headless=True)
    except Exception:
        return p.chromium.launch(headless=True, channel="chrome")


def main():
    with sync_playwright() as p:
        browser = launch_browser(p)
        page = browser.new_page()
        page.set_content(HTML)
        out = page.evaluate("window.runLab()")
        browser.close()

    expected = {
        "camel_case_and_prevent_default": {
            "return_false_prevented_default": False,
            "prevent_default_cancelled": True,
            "synthetic_event_types": ["click", "click"],
        },
        "toggle_class_bind_this": {
            "toggle_sequence": ["ON", "OFF", "ON"],
            "unbound_this_type": "undefined",
        },
        "class_field_arrow_vs_inline_arrow": {
            "field_arrow_this_ok": True,
            "field_arrow_same_ref": True,
            "inline_arrow_this_ok": True,
            "inline_arrow_same_ref": False,
        },
        "passing_arguments_arrow_vs_bind": {
            "calls": [
                {"method": "deleteRow", "id": 101, "eventType": "click"},
                {"method": "deleteRow", "id": 202, "eventType": "click"},
                {"method": "preventPop", "name": "Hello world!", "eventType": "click", "prevented": True},
            ],
            "link_default_prevented": True,
        },
    }
    actuals = {
        "camel_case_and_prevent_default": out["case1"],
        "toggle_class_bind_this": out["case2"],
        "class_field_arrow_vs_inline_arrow": out["case3"],
        "passing_arguments_arrow_vs_bind": out["case4"],
    }
    cases = [
        {"name": name, "expected": expected[name], "actual": actuals[name], "passed": actuals[name] == expected[name]}
        for name in expected
    ]
    print(json.dumps({"cases": cases}, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()
本例需在 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。

入口文件:projects/react-event-handle-lab/explore-event-handle.py

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-event-handle.py,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、CPython 3.12.14、Playwright 与本地浏览器/标准库。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:React

课程关联工程包(登记关联42章) · 含当前章节或实例 · mbskycom202612a3152.zip

下载课程关联工程包:React

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3171.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习