![](/img/trans.png)
[英]how to set react parent component state by a async function and then pass this state to child as props?
[英]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.