React Hooks - 如何将道具从子组件传递到父组件?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了React Hooks - 如何将道具从子组件传递到父组件?相关的知识,希望对你有一定的参考价值。
在下面的例子中,我怎样才能通过 imageAsUrl.imgUrl
从子组件(ImageUpload)到父组件(UpdateCard)。
子组件
import React, useState, useEffect from 'react';
import storage from '../firebase';
const ImageUpload = () =>
const allInputs = imgUrl: '' ;
const [imageAsUrl, setImageAsUrl] = useState(allInputs);
const [image, setImage] = useState(null);
const handleChange = (e) =>
if (e.target.files[0])
setImage(e.target.files[0]);
;
useEffect(() =>
if (image)
const uploadTask = storage.ref(`images/$image.name`).put(image);
uploadTask.on(
'state_changed',
(snapshot) => ,
(error) =>
console.log(error);
,
() =>
storage
.ref('images')
.child(image.name)
.getDownloadURL()
.then((fireBaseUrl) =>
setImageAsUrl((prevObject) => (
...prevObject,
imgUrl: fireBaseUrl,
));
);
);
, [image]);
return (
<>
<label className='custom-file-upload'>
<input type='file' onChange=handleChange />
</label>
<img src=imageAsUrl.imgUrl alt='sample' />
</>
);
;
export default ImageUpload;
PARENT组件
import React, useState from 'react';
import firebase from '../firebase';
import ImageUpload from './ImageUpload';
const UpdateCard = ( card ) =>
const [originalText, setOriginalText] = useState(card.originalText);
const [translatedText, setTranslatedText] = useState(card.translatedText);
const onUpdate = () =>
const db = firebase.firestore();
db.collection('FlashCards')
.doc(card.id)
.set( ...card, originalText, translatedText );
timeOutScroll();
;
return (
<>
<div>
card.imageURL ? (
<img src=card.imageURL alt='' className='img' />
) : (
<textarea
className='upload-textarea'
value=originalText
onChange=(e) =>
setOriginalText(e.target.value);
/>
)
<ImageUpload />
</div>
<textarea
value=translatedText
onChange=(e) =>
setTranslatedText(e.target.value);
/>
<button onClick=onUpdate>Update</button>
</>
);
;
export default UpdateCard;
答案
在父组件中,你可以定义一个回调函数作为道具ref,在子组件中调用。
const ImageUpload = (getURLtoParent) => <--------------------
const [imageAsUrl, setImageAsUrl] = useState(allInputs);
useEffect(() =>
uploadTask.on(
..............
...
);
if(imageAsUrl.imgUrl !== '')
getURLtoParent(imageAsUrl.imgUrl) <-----------------------
,[image])
const UpdateCart = () =>
const[imgURL,setimgURL] = useState(null)
return (
......
<ImageUpload getURLtoParent= (url) => setimgURL(url) /> <----------------
.........
)
以上是关于React Hooks - 如何将道具从子组件传递到父组件?的主要内容,如果未能解决你的问题,请参考以下文章
使用 React Hooks 获取帖子并将它们作为附加道具传递给另一个组件