繁体   English   中英

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

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

我最近开始使用打字稿,但在传递使用状态设置器函数时遇到了麻烦,

我的父组件是这样的:

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

在孩子中,我正在路过:

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

孩子有这个:

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

我不断收到错误消息: 在此处输入图像描述

您忘记添加花括号

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

要么使用道具,要么解构道具

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

解构

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

只需使用setword: (word: string) => void作为道具类型。

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

我建议不要让你的生活变得更艰难,而是使用以下方法:

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