Home  >  Q&A  >  body text

In Astro, I tried to rewrite the Preact component from function to class

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粉006540600P粉006540600249 days ago397

reply all(1)I'll reply

  • P粉111641966

    P粉1116419662024-01-17 18:36:03

    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>
          </>
        );
      }
    }

    reply
    0
  • Cancelreply