简体   繁体   中英

How to create an array in react with typescript?

I tried to create an array in each click using ReactJS and Typescript. Here's my code:

const FormTags: React.FC = () => {
     const [selected, setSelected] = React.useState<[]>([])

     const handleTag = (e: React.FormEvent<HTMLInputElement>) => {
             let id: number = +e.currentTarget.value
             //working, show me each id
             console.log(id)
             // not working
             setSelected([...id]) // error here
             // Argument of type 'number' is not assignable to parameter of type 
             // 'SetStateAction<[]>'.
     }

     //retrieve tags working well, show me all list tags
     return (
        <form>
            {tags && tags.map(tag: any) => (
                <label key={tag.id}>
                    <input type="checkbox" value={tag.id} onClick={handleTag}/>
                </label>
            )}
       </form>
    )
}

I want to build an array like this [1, 2, 3, ...] in each click get ID of the tags and persist it with setSelected . How can I do it?

I think that's what you want:

const FormTags: React.FC = () => {
  const [selected, setSelected] = React.useState<number[]>([]);

  const handleTag = (e: React.FormEvent<HTMLInputElement>) => {
    const id: number = +e.currentTarget.value;
    const { checked } = e.currentTarget;

    if (checked) {
      setSelected(prev => [...prev, id]);
    } else {
      setSelected(prev => prev.filter(item => item !== id));
    }
  };

  return (
    <form>
      {tags &&
        tags.map((tag: any) => (
          <input
            checked={selected.includes(tag.id)}
            type="checkbox"
            value={tag.id}
            onClick={handleTag}
          />
        ))}
    </form>
  );
};

When you check the checkbox, its id will be added to the select state. If you uncheck, the id will be removed.

The problem in your code was that you were trying to destruct the id, which is a number, when actually you must destruct the previous array and then add the id. This can be easily done passing to setSelect a function that will receive the previous state and return the new state.

setSelected(prev => [...prev, id]);

Check the React documentation for more info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM