简体   繁体   中英

React/Typescript : how to type a value in a setter with onChange

i'm new with react/typescript and i have a problem to "type" a value with an Onchange. here's the code:

    interface Props {
  race : CharacterRace | '',
  classe : CharacterClass | '',
  sexe : CharacterGender | '',
  setRace : (race : CharacterRace | '')=>void,
  setClasse : (classe : CharacterClass | '')=>void,
  setSexe : (sexe: CharacterGender | '')=>void
}
...
          <select name="race" id="race" value={props.race} onChange={({ target: { value } })=>props.setRace(value)}>
        <option value=""> </option>
        <option value="humains">Humain</option>
        <option value="elfes">Elfe</option>
        <option value="orcs">Orc</option>
        <option value="mort-vivants">Mort-Vivant</option>
        <option value="nains">Nain</option>
      </select>

He told me that "value" is a string and can't be assigned to CharacterRace | ''

if I make this:

 setClasse : (classe : CharacterClass | string)=>void,

That "solve" the problem, but it's just a hack, it's not clean

I try to type the "value" but it didn't work

Do you have an idea how I can fix that?

The type:

    export type CharacterRace = 'humains' | 'elfes' | 'orcs' | 'mort-vivants' | 'nains';

    export type CharacterClass = 'guerrier' | 'barbare' | 'paladin' | 'rodeur' | 'voleur' | 'mage' | 'pretre' | 'guerrier-mage';
    
    export type CharacterGender = 'masculin' | 'feminin';

You should use "HTMLInputElement"

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