In Astro, I tried to rewrite the Preact component from function to class
P粉006540600
P粉006540600 2024-01-16 23:12:28
0
1
451

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!

P粉006540600
P粉006540600

reply all(1)
P粉111641966

Signal tracing cannot be performed through such a constructor. You need to switch to arrow functions and manipulate the incoming signal directly:

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>
      </>
    );
  }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template