這裡有一個示範儲存庫,展示如何將 Preact 與 Astro 結合使用
我將在這裡僅顯示相關的程式碼片段。在astro頁面檔案中,preact元件的使用如下
--- ... const count = signal(0); ... --- <Counter count={count} client:visible> <h1>Hello, Preact 1!</h1> </Counter>
在該儲存庫中,preact 定義如下:
export default function Counter({ children, count }) { const add = () => count.value++; const subtract = () => count.value--; return ( <> <div class="counter"> <button onClick={subtract}>-</button> <pre>{count}</pre> <button onClick={add}>+</button> </div> <div class="counter-message">{children}</div> </> ); }
現在,我想將此元件重寫為一個類別:
export default class Counter extends Component { constructor(props: any) { super(props); this.add = this.add.bind(this); this.subtract = this.subtract.bind(this); } add() { (this.props as any).count.value++; } subtract() { (this.props as any).count.value--; } render({ children, count }: any) { return ( <> <div class="counter"> <button onClick={this.subtract}>-</button> <button onClick={this.add}>+</button> </div> <div class="counter-message">{children}</div> </> ); } }
問題是,當我單擊 或 - 時沒有任何反應,似乎信號
不再起作用。所以我一定是做了一些根本性錯誤的事情(請注意,我是一個 React NooP!)任何幫助將不勝感激!
P粉1116419662024-01-17 18:36:03
訊號追蹤無法透過這樣的建構函式進行。您需要切換到箭頭函數並直接操作傳入的訊號:
export default class Counter extends Component { add = () => { this.props.count.value++; } subtract = () => { this.props.count.value--; } render({ children, count }: any) { return ( <> <div class="counter"> <button onClick={this.subtract}>-</button> <button onClick={this.add}>+</button> </div> <div class="counter-message">{children}</div> </> ); } }