Get image preview before uploading in React

前端 未结 9 1756
醉梦人生
醉梦人生 2020-12-04 17:51

Many examples of this on here but can\'t seem to find any for react. I have managed to convert the vanilla js to react but getting an error.

The answer looks simple

9条回答
  •  广开言路
    2020-12-04 18:46

    There is my solution. Very simple and easy to use.

    JSX

    And function

      _onChange = (e) => {
    
        const file    = this.refs.uploadImg.files[0]
        const reader  = new FileReader();
    
        reader.onloadend = () => {
            this.setState({
                imageUrl: reader.result
            })
        }
        if (file) {
            reader.readAsDataURL(file);
            this.setState({
                imageUrl :reader.result
            })
        } 
        else {
            this.setState({
                imageUrl: ""
            })
        }
    }
    

    And of course You need to have state like imageUrl which is our src in jsx.

提交回复
热议问题