weikee94 / react-ts

react with typescript
0 stars 0 forks source link

Async Event #4

Open weikee94 opened 3 years ago

weikee94 commented 3 years ago

see more

import * as React from 'react';
import { fetchDogFacts, DogFactType } from './dog-facts';

// 这里我们自己声明onSubmit take n as a number and just execute without return anything 
type FormProps = {
  onSubmit: (n: number) => void;
};

const Form = ({ onSubmit }: FormProps) => {
  const [value, setValue] = React.useState(1);

  // 只有自己声明function 才要写event:  React.FormEvent<HTMLFormElement>
  // inline 可以不用写 ts 会自己detect
  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    onSubmit(value);
  };

  return (
    <form onSubmit={handleSubmit}>
      <div className="fact-input">
        <label htmlFor="number-of-facts">Number of Dog Facts</label>
        <input
          type="number"
          value={value}
          min="1"
          max="10"
          onChange={(event) => setValue(+event.target.value)}
          id="number-of-facts"
        />
      </div>
      <input type="submit" value="Fetch Dog Facts" />
    </form>
  );
};

const Fact = ({ fact }: { fact: string }) => {
  return (
    <article className="dog-fact">
      <h3>Dog Fact</h3>
      <p>{fact}</p>
    </article>
  );
};

// 如果没有define DogFactType 会是 never[]
// 如果没有define FormProps 会报错

const Application = () => {

  const [facts, setFacts] = React.useState<DogFactType[]>([]);

  const handleSubmit = (n: number) => {
    fetchDogFacts(n).then((facts) => {
      setFacts(facts);
    });
  };

  return (
    <main>
      <Form onSubmit={handleSubmit} />
      <section>
        {facts.map((fact, index) => (
          <Fact key={index} fact={fact.fact} />
        ))}
      </section>
    </main>
  );
};

export default Application;