简体   繁体   English

如何更改图像 src?

[英]How can I change image src?

I'm trying to change the image and using it as user profile photo in firebase我正在尝试更改图像并将其用作 firebase 中的用户个人资料照片

I can upload the images to storage but I can't take their url's using the code below我可以将图像上传到存储,但我不能使用下面的代码获取他们的网址

storage
 .ref("images")
 .child(image.name)
 .getDownloadURL()
 .then(url => {
  setUrl(url)
})

Then I want to use that url to change the image src然后我想用那个url来改变图像src

const upUserPhoto = () => {user.updateProfile({photoURL: url})} <img src={user.photoURL}/> const upUserPhoto = () => {user.updateProfile({photoURL: url})} <img src={user.photoURL}/>

but it didn't work..How can I fix this and is there better way to make this?但它没有用..我该如何解决这个问题,有没有更好的方法来做到这一点? Please enlighten me.请赐教。

Whole code整个代码

import React, { useState } from 'react'
import fire from "./fire"


function Profilephoto({ open, children, onClose }) {
    const[image, setImage] = useState(null)
    const[url, setUrl] = useState("")
    const[progress, setProgress] = useState(0)
    const storage = fire.storage();
    const user = fire.auth().currentUser
    if (!open) return null

    

    const asdChange = (e) => {
        if(e.target.files[0]) {
            setImage(e.target.files[0])
        }
    }

    const asdUpload = () => {
        const uploadTask = storage.ref(`ìmages/${image.name}`).put(image)
        uploadTask.on(
            "state_changed",
            snapshot => {
                const progress= Math.round(
                    (snapshot.bytesTransferred/snapshot.totalBytes) * 100
                )
                setProgress(progress)
            },
            error => {
                console.log("error")
            },
            () => {
                storage
                    .ref("images")
                    .child(image.name)
                    .getDownloadURL()
                    .then(url => {
                        setUrl(url)
                    })
            }
        ) 
    }

    const setProfile = () => {
        user.updateProfile({photoURL: url})
    }

    
    
    return (
        <>
        <div className="modalb"></div>

        <div className="modala">
            
            <progress value={progress} max="100"/>
            
            <input type="file" onChange={asdChange}/>

            <button onClick={asdUpload}>Upload</button>

            <form onSubmit={setProfile}>
                <input type="submit" value="Add"/>
            </form>
            
            <img src={url} width="250rem" height="250rem" alt="error"/>

            
            <button  onClick={onClose}>Close</button>
            {children}
        </div>
        </>
    )
}

export default Profilephoto

Make something like that, that listen your setUrl like useEffect制作类似的东西,像 useEffect 一样听你的useEffect

useEffect({
    setProfile()
}, [url]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM