这里有一个演示存储库,展示了如何将 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!)任何帮助将不胜感激!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
信号跟踪无法通过这样的构造函数进行。您需要切换到箭头函数并直接操作传入的信号:
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> </> ); } }