streamlit_lit_web_component.py
· 1.8 KiB · Python
Surowy
import streamlit as st
import streamlit.components.v1 as components
st.title("使用 Lit Web Component (無 CDN)")
lit_component = """
<script type="module">
class MyLitComponent extends HTMLElement {
constructor() {
super();
this.attachShadow({ mode: 'open' });
this.shadowRoot.innerHTML = `
<style>
:host {
display: block;
text-align: center;
padding: 10px;
border: 2px solid #007bff;
border-radius: 8px;
background-color: #f8f9fa;
width: 100%;
max-width: 400px;
margin: auto;
}
h2 {
color: #007bff;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
background-color: #007bff;
color: white;
border: none;
border-radius: 4px;
margin-top: 10px;
}
</style>
<h2>這是一個 Lit Web Component</h2>
<p>使用 Lit 來建立的自訂元件</p>
<button id="btn">點擊我</button>
`;
this.shadowRoot.getElementById("btn").addEventListener("click", () => {
alert("你點擊了 Lit 按鈕!");
});
}
}
customElements.define('my-lit-component', MyLitComponent);
</script>
<my-lit-component></my-lit-component>
"""
components.html(lit_component, height=250)
| 1 | import streamlit as st |
| 2 | import streamlit.components.v1 as components |
| 3 | |
| 4 | st.title("使用 Lit Web Component (無 CDN)") |
| 5 | |
| 6 | lit_component = """ |
| 7 | <script type="module"> |
| 8 | class MyLitComponent extends HTMLElement { |
| 9 | constructor() { |
| 10 | super(); |
| 11 | this.attachShadow({ mode: 'open' }); |
| 12 | this.shadowRoot.innerHTML = ` |
| 13 | <style> |
| 14 | :host { |
| 15 | display: block; |
| 16 | text-align: center; |
| 17 | padding: 10px; |
| 18 | border: 2px solid #007bff; |
| 19 | border-radius: 8px; |
| 20 | background-color: #f8f9fa; |
| 21 | width: 100%; |
| 22 | max-width: 400px; |
| 23 | margin: auto; |
| 24 | } |
| 25 | h2 { |
| 26 | color: #007bff; |
| 27 | } |
| 28 | button { |
| 29 | padding: 10px 20px; |
| 30 | font-size: 16px; |
| 31 | cursor: pointer; |
| 32 | background-color: #007bff; |
| 33 | color: white; |
| 34 | border: none; |
| 35 | border-radius: 4px; |
| 36 | margin-top: 10px; |
| 37 | } |
| 38 | </style> |
| 39 | <h2>這是一個 Lit Web Component</h2> |
| 40 | <p>使用 Lit 來建立的自訂元件</p> |
| 41 | <button id="btn">點擊我</button> |
| 42 | `; |
| 43 | this.shadowRoot.getElementById("btn").addEventListener("click", () => { |
| 44 | alert("你點擊了 Lit 按鈕!"); |
| 45 | }); |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | customElements.define('my-lit-component', MyLitComponent); |
| 50 | </script> |
| 51 | |
| 52 | <my-lit-component></my-lit-component> |
| 53 | """ |
| 54 | |
| 55 | components.html(lit_component, height=250) |
| 56 |