master
Evan Chen 2022-07-15 23:04:59 +08:00
parent cc27b07ce6
commit f1698b4cb2
2 changed files with 35 additions and 13 deletions

View File

@ -13,7 +13,7 @@
</head>
<body>
<wc-test></wc-test>
<wc-test id='test' name='Evan'></wc-test>
</body>
<script src="dist/index.js"></script>
</html>

View File

@ -4,35 +4,57 @@ import ReactDOM from 'react-dom/client';
import logo from './logo.svg';
const WcTestApp = () => {
const WcTestApp = (props) => {
const [ctr,incr] = useState(0)
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<p>Hello! {props.name}.</p>
<Button label={`clicked ${ctr} times`} icon="pi pi-check" onClick={()=>{incr(ctr+1)}}/>
</header>
</div>
);
}
WcTestApp.defaultProps = {
name: 'World'
};
// a wrapper class for react component
class WcTest extends HTMLElement {
root;
// declare attributes we want to keep track of
static get observedAttributes() {
return ['name', 'onclick'];
}
connectedCallback() {
const mountPoint = this;
// to get attributes from outside
// const name = this.getAttribute('name');
let mountPoint = this;
// ShadowRoot (global styles will not apply, but safer with a complete isolation layer)
// this.attachShadow({ mode: 'open' }).appendChild(mountPoint);
// mountPoint = this.attachShadow({ mode: 'open' });
const root = ReactDOM.createRoot(mountPoint);
// render
root.render(<WcTestApp />);
this.root = ReactDOM.createRoot(mountPoint);
this.render()
}
render(){
const name = this.hasAttribute('name')
? this.getAttribute('name')
: undefined;
console.log(this.root)
this.root.render(<WcTestApp name={name} />);
}
attributeChangedCallback(){
this.render()
}
}
customElements.define('wc-test', WcTest);