Rumah > Soal Jawab > teks badan
Saya ada komponen TopPage
和 ImagePreview
和 FileUploader
Tunjuk dulu FileUploader
,
FileUploader menukar keadaan fileObj TopPage.
Kemudian, FileUploader hilang, ImagePreview muncul, dan useEffect() dipanggil pada masa yang sama, tetapi tiada ImagePreviewRef
pada masa ini.
Apabila useState dipanggil, kedua-dua pemaparan semula komponen dan useEffect akan dipanggil.
Arahannya ialah useEffect -> render semula?
Jika ya, bagaimana saya boleh menyelesaikan masalah ini?
const TopPage = (props) =>{ const [fileObj, setFileObj ] = useState(); const imagePreviewRef = useRef(); useEffect(() =>{ console.log("useEffect() is called with fileObj:",fileObj); console.log("imagePrevireRef.current is ready?",imagePreviewRef.current); imagePreviewRef.current.loadPic(fileObj); },[fileObj]); if (fileObj){ return <ImagePreview ref={imagePreviewRef}></ImagePreview> } else { return <FileUploader SetFileObj=setFileObj></FileUploader> } } const FileUploader = (props) => { // props.setFileObj() is called here. } const ImagePreview = (props) => { const loadPic = () =>{// loadpicture to canvas } }
Penyelesaian sementara,
Saya melakukan seperti ini setakat ini,
Memaparkan ImagePreview
dan ImagePreview
和 FileUploader
Komponen ditukar melalui display:none
dari mula.
Nampak janggal sikit...tapi berkesan setakat ini.
const TopPage = (props) =>{ const [fileObj, setFileObj ] = useState(); const imagePreviewRef = useRef(); useEffect(() =>{ console.log("useEffect() is called with fileObj:",fileObj); console.log("imagePrevireRef.current is ready?",imagePreviewRef.current); imagePreviewRef.current.loadPic(fileObj); },[fileObj]); if (fileObj){ return <React.Fragment> <div style={{display:"block"}}> <ImagePreview ref={imagePreviewRef}></ImagePreview> </div> <div style={{display:"none"}}> <FileUploader SetFileObj=setFileObj></FileUploader> </div> </React.Fragment> } else { return <React.Fragment> <div style={{display:"none"}}> <FileUploader SetFileObj=setFileObj></FileUploader> </div> <div style={{display:"block"}}> <ImagePreview ref={imagePreviewRef}></ImagePreview> </div> </React.Fragment> } } const FileUploader = (props) => { // props.setFileObj() is called here. } const ImagePreview = (props) => { const loadPic = () =>{// loadpicture to canvas } }
P粉1655228862024-03-23 00:36:53
Render secara seragam, kemudian gunakan CSS untuk memaparkan komponen secara bersyarat untuk mengekalkan rujukan.
const TopPage = (props) =>{ const [fileObj, setFileObj ] = useState(); const imagePreviewRef = useRef(); useEffect(() =>{ if(imagePreviewRef.current) imagePreviewRef.current.loadPic(fileObj); },[fileObj]); return ( <>{fileObj &&} > ) }