簡體   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