[英]Unexpected token '<' when trying to load my webcomponent in html
所以我試圖創建一個反應 web 組件。 我將它包裝起來,在 VSCode 上看起來不錯,但是當我嘗試加載它時,它給了我錯誤:行上出現意外的標記“<”:
ReactDOM.render(<Counter/>, mountPoint);
有誰知道為什么以及如何解決它? 謝謝
這是我的網絡組件:
import React from 'react';
import * as ReactDOM from 'react-dom';
import Counter from './counter';
class CounterWC extends HTMLElement {
connectedCallback() {
// Create a ShadowDOM
const root = this.attachShadow({ mode: 'open' });
// Create a mount element
const mountPoint = document.createElement('div');
root.appendChild(mountPoint);
// You can directly use shadow root as a mount point
ReactDOM.render(<Counter/>, mountPoint);
}
}
customElements.define('counter-wc', CounterWC)
這是我的 html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-9" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>React webcomponent:</h1>
<counter-wc></counter-wc>
<script type="module" src="./counterWC.js"></script>
</body>
</html>
回復:評論
您將文件命名為 *.js 並不意味着它是JavaScript
ReactDOM.render(<Counter/>, mountPoint);
是 JSX,不是JavaScript,它需要在構建步驟中轉換為 JavaScript。
或者根本不使用 React:
class CounterWC extends HTMLElement { constructor(){ super().attachShadow({mode: 'open'}).append(this.div = document.createElement('div')); } connectedCallback() { this.div.innerHTML = `Am I a counter?`; } } customElements.define('counter-wc', CounterWC);
<counter-wc></counter-wc>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.