我仍然有问题打字和反应,所以请屈尊。提前谢谢你们。
我正在尝试传输一个函数和一个对象到一个组件
这是我的组件WordItem
import React, {FC, useContext} from "react"
import { IWord } from "../../../models/IWord"
import {Context} from "../../../index";
const WordItem: FC<IWord> = (word) => {
const {store} = useContext(Context)
async function deleteWord () {
await store.deleteWord(word.id)
}
return (
<div key={word.id}>
<div>
<div>{word.word}</div>
<div>{word.wordT}</div>
</div>
<div>
<div>{word.instance}</div>
<div>{word.instanceT}</div>
<button onClick={() => {deleteWord()}}>delete</button>
</div>
</div>
)
}
export default WordItem
这是我的App.tsx
文件:
import React, {FC, useContext, useState} from 'react';
import {Context} from "./index";
import {observer} from "mobx-react-lite";
import {IUser} from "./models/IUser";
import WordService from "./services/WordService"
import { IWord } from './models/IWord';
import WordItem from './components/UI/word/WordItem';
const App: FC = () => {
const {store} = useContext(Context)
const [users, setUsers] = useState<IUser[]>([])
const [words, setWords] = useState<IWord[]>([])
async function getWords() {
try {
const response = await WordService.fetchWords()
setWords(response.data)
} catch (e) {
console.log(e)
}
}
return (
<div>
<button onClick={getWords}>Get words</button>
{words.reverse().map(word => <WordItem {...word}/>)}
{words.length == 0? 'there is no words': ''}
</div>
)
}
export default observer(App);
正如你所看到的,我成功地在一个组件中传输了对象word
,但我真的不知道如何传输一个函数。<WordItem {getWords, ...word}/>
或<WordItem getWords={getWords} { ...word}/>
不起作用。比如如何正确地将它们放入<WordItem/>
如果您想将word
变量和getWords
函数都传递给WordItem
组件,您应该按照以下步骤执行:
<WordItem word={word} getWords={getWords} />
然后你需要调整你的组件道具类型来匹配这些道具:
const WordItem: FC<{word: IWord, getWords: () => Promise<void>}> = ({word, getWords}) => {
...
我在上面的代码中使用对象解构来从prop
参数中获得两个道具,这相当于做以下事情:
const WordItem: FC<{word: IWord, getWords: () => Promise<void>}> = (props) => {
const word = props.word;
const getWords = props.getWords;
...