如何渲染上载的图像(图像对象)而不出现错误

我试图在React组件中设置一个图像加载器,以在加载后显示/渲染它(仅客户端,没有http请求)。图像作为对象加载,导致渲染错误:“对象作为React子代无效”


import React, { Component } from "react";


export default class extends Component {

    state = {

        selectedImage: null

    }



    onChange = (event) => {

        this.setState({

            selectedImage: event.target.files[0],

        })

    }



    render() {

        return (

            <div>


                <div>

                    {this.state.selectedImage && this.state.selectedImage}

                </div>


                <form onSubmit={this.onFormSubmit}>

                    <input type="file" name="someImage" accept="image/*" onChange={this.onChange} />

                    <button>Add This Car</button>

                </form>

            </div>

        )

    }

}

预期结果-加载的图像在屏幕上显示/渲染。实际结果-错误:“对象作为React子对象无效” ...


RISEBY
浏览 224回答 1
1回答

慕盖茨4494581

上传的文件无法显示,您需要<img />带src属性的标记src可以通过读取以下内容来生成属性的值event.target.files[0]这样的事情应该做:import React, { Component } from "react";export default class extends Component {&nbsp; &nbsp; constructor(props) {&nbsp; &nbsp; &nbsp; &nbsp; super(props);&nbsp; &nbsp; &nbsp; &nbsp; this.state = {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedImage: null.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedImageContent: ""&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; onChange = (event) => {&nbsp; &nbsp; &nbsp; &nbsp; const file = event.target.files[0];&nbsp; &nbsp; &nbsp; &nbsp; const fileReader = new FileReader();&nbsp; &nbsp; &nbsp; &nbsp; fileReader.onload = this.onFileLoad;&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedImage: event.target.files[0]&nbsp; &nbsp; &nbsp; &nbsp; })&nbsp; &nbsp; };&nbsp; &nbsp; onFileLoad = (e) => {&nbsp; &nbsp; &nbsp; &nbsp; this.setState({&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; selectedImageContent: e.target.result&nbsp; &nbsp; &nbsp; &nbsp; });&nbsp; &nbsp; }&nbsp; &nbsp; render() {&nbsp; &nbsp; &nbsp; &nbsp; const { selectedImageContent } = this.state;&nbsp; &nbsp; &nbsp; &nbsp; return (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {selectedImageContent && <img src={selectedImageContent} />}&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <form onSubmit={this.onFormSubmit}>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="file" name="someImage" accept="image/*" onChange={this.onChange} />&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button>Add This Car</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; }}更多信息在这里
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript