Here is a demo repository showing how to use Preact with Astro
I will only show relevant code snippets here. In the astro page file, the preact component is used as follows
--- ... const count = signal(0); ... --- <Counter count={count} client:visible> <h1>Hello, Preact 1!</h1> </Counter>
In this repository, preact is defined as follows:
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> </> ); }
Now, I want to rewrite this component into a class:
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> </> ); } }
The problem is that when I click the or - nothing happens, it seems the signal
no longer works. So I must be doing something fundamentally wrong (note, I'm a React NooP!) Any help would be greatly appreciated!
Signal tracing cannot be performed through such a constructor. You need to switch to arrow functions and manipulate the incoming signal directly: