简体   繁体   中英

how to pass useState set state function to a child component in typescript?

I recently started using typescript and I'm having trouble with passing a use state setter function,

my parent component is is this :

const [word, setword] = useState('run')

and in the child im passing :

<Child word={word} setword={setword}/>

the child has this :

    interface Props {
      word: string
      
      setword: React.Dispatch<React.SetStateAction<string>>;
    }
    const VoicetoText: React.FC<Props> = (word, setword) => {
    return (
{word}
<button onClick={()=>setword('hey buddy')} ><button/>
    )}

i keep getting an error : 在此处输入图像描述

You forgot to add a curly brace to

const VoicetoText: React.FC<Props> = (word, setword) 

either use props or deconstruct the props

const VoicetoText: React.FC<Props> = (props) 
props.setWord

deconstruct

const VoicetoText: React.FC<Props> = ({word, setword}) 

Just use setword: (word: string) => void as the prop type.

interface Props {
  word: string      
  setword: (word: string) => void;
}

I would suggest to not make your life harder and go wtih something like:

const Child = ({setWord}: {setWord: (arg0: string}) => void) => {
  // () => setWord("word") is jsut for sample sake, you should avoid using arrow function calls inside event handleres like this
  return <button onClick={() => setWord("word")}>Click me</button>
}

const Parent = () => {

  const [word, setWord] = useState(false);

  return <Child propName={setWord}/>
}

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