我在react和typescript方面有点新,并且在从文件App.tsx
到名为WordAddingForm.tsx
的功能组件的传输功能方面有一点问题提前感谢!
这是我的App.tsx
文件:
import React, {FC, useState} from 'react';
import WordAddingForm from './components/WordAddingForm';
import {observer} from "mobx-react-lite";
import WordService from "./services/WordService"
const App: FC = () => {
const {store} = useContext(Context)
const [words, setWords] = useState<IWord[]>([])
async function getWords() {
try {
const response = await WordService.fetchWords()
setWords(response.data)
} catch (e) {
console.log(e)
}
}
return (
<div>
<div><WordAddingForm/></div>
</div>
)
}
export default observer(App);
我需要将函数getWords
传输到组件这是我的WordAddingForm.tsx
文件:
import React, {FC, useContext, useState} from 'react';
import {Context} from "../index";
import {observer} from "mobx-react-lite";
import WordService from '../services/WordService';
const WordAddingForm: FC = () => {
const [word, setWord] = useState<string>('')
const [wordT, setWordT] = useState<string>('')
const [instance, setInstance] = useState<string>('')
const [instanceT, setInstanceT] = useState<string>('')
const {store} = useContext(Context)
function clear():void {
setWord('')
setWordT('')
setInstance('')
setInstanceT('')
}
async function createWord(word:string, wordT:string, instance:string, instanceT:string) {
try {
const response = await store.createWord(word, wordT, instance, instanceT)
console.log(response)
clear()
} catch (e) {
console.log(e)
}
}
return (
<div>
<input
onChange={e => setWord(e.target.value)}
value={word}
type="text"
placeholder="word"
/>
<input
onChange={e => setWordT(e.target.value)}
value={wordT}
type="text"
placeholder="word translation"
/>
<input
onChange={e => setInstance(e.target.value)}
value={instance}
type="text"
placeholder="instance of using this word"
/>
<input
onChange={e => setInstanceT(e.target.value)}
value={instanceT}
type="text"
placeholder="instance translation"
/>
<button
onClick={() => {
createWord(word, wordT, instance, instanceT)
clear()
}}>
add word +
</button>
</div>
)
}
export default observer(WordAddingForm)
并且我需要将函数getWords
传输到<WordAddingForm/>
以在此组件中使用它,并在向数据库添加新词后再次更新单词列表如<WordAddingForm props={getWords}/>
或<WordAddingForm {getWords}/>
没有帮助
<WordAddingForm getWords={getWords} />
这是你传递给组件的方式。当在WordAddingForm
内部使用时,您必须通过参数接收props对象:
interface Props {
getWords: () => Promise<any>
}
const WordAddingForm: FC<Props> = (props) => {
// use your function as props.getWords()
}