简体   繁体   English

如何将useState设置状态函数传递给打字稿中的子组件?

[英]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.只需使用setword: (word: string) => void作为道具类型。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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