React:单击按钮从目录中的静态位置加载图像

React: Click button to load image from static location in directory

当用户点击屏幕上的“示例 1”按钮时,它应该加载并显示位于本地的图像。

这是我尝试过的方法,但它不起作用

import React, {Component} from 'react';
import image_1 from "../../static_media/1.png"
import image_2 from "../../static_media/2.png"
import {Container, Image} from "react-bootstrap";


class Classifier extends Component {
    state = {
        files: [],
        isLoading: false,
        recentImage: null,
    }


    handleClick = (e) => {

        const ImageData = [image_1, image_2]

        const FILES = {
            "image_1": [{
                name: "image_1",
                size: "100",
                image: ImageData[0]
            }],
            "image_2": [{
                name: "image_2",
                size: "200",
                image: ImageData[1]
            }],
            "image_3": [{
                name: "image_3",
                size: "300",
                image: ImageData[1]
            }],
        }

        // you can now use this value to load your images
        const prefix = e.target.dataset.prefix; // 1
        this.setState({
            files: [],
            isLoading: true,
            recentImage: null
        })
        this.loadImage(FILES[`image_${prefix}`])
    }

    loadImage = (files) => {
        setTimeout(() => {
            this.setState({
                files,
                isLoading: false
            }, () => {
                console.log(this.state.files[0])
            })
        }, 1000);
    }

    render() {
        const files = this.state.files.map(file => (
            <li key={file.name}>
                {file.name} - {file.size} bytes
            </li>
        ));
        return (

            <Container>

                <button
                    data-prefix="1"
                    onClick={(e) => this.handleClick(e)}
                    className="btn btn-primary">
                    Sample 1
                </button>
                <aside>
                    {files}
                </aside>

                <div className="img-fluid">
                    {this.state.files.length > 0 &&
                    <Image
                        src={URL.createObjectURL(this.state.files[0])}
                        height='400' rounded/>
                    }
                </div>
            </Container>


        )
    }
}

export default Classifier;

我收到一个错误

TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.

78 | 79 | {this.state.files.length

0 && 80 | <Image 81 | src={URL.createObjectURL(this.state.files[0])} | ^ 82 | height='400' rounded/> 83 | } 84 |

理想情况下,我想创建一个实际的图像对象,以便能够将此图像发送到 Django REST API。

您需要手动指定图像信息,否则您将需要额外的步骤来动态获取文件大小。

const FILES = {
    "image_1": [{
        name: "image_1",
        size: "100",
        image: require("../../static_media/1.png").default
    }],
    "image_2": [{
        name: "image_2",
        size: "200",
        image: require("../../static_media/2.png").default
    }],
}

为每个按钮添加数据属性和点击事件,

<button 
       ...
       data-prefix="1" 
       onClick={(e) => this.handleClick(e)}> Sample 1</button>



    handleClick = (e) => {
        // you can now use this value to load your images
        const prefix = e.target.dataset.prefix; // 1
        this.setState({
            files: [],
            isLoading: true,
            recentImage: null
        })
        this.loadImage(FILES[`image_${prefix}`])
    }

您需要 URL.createObjectURL() 的 Blob 或 File 对象。 (你可以在这里阅读 URL.createObjectURL() a link

创建 Blob 对象的最简单方法是使用 Fetch API。

import React, {Component} from 'react';
import image_1 from "../../static_media/1.png"
import image_2 from "../../static_media/2.png"
import {Container, Image} from "react-bootstrap";


class Classifier extends Component {
    state = {
        files: [],
        isLoading: false,
        recentImage: null,
    }


    handleClick = async (e) => {

        const ImageData = [image_1, image_2]

        const FILES = {
            "image_1": [{
                name: "image_1",
                size: "100",
                image: await fetch(ImageData[0]).then(res => res.blob()) 
            }],
            "image_2": [{
                name: "image_2",
                size: "200",
                image: await fetch(ImageData[1]).then(res => res.blob())
            }],
            "image_3": [{
                name: "image_3",
                size: "300",
                image: await fetch(ImageData[1]).then(res => res.blob())
            }],
        }

        // you can now use this value to load your images
        const prefix = e.target.dataset.prefix; // 1
        this.setState({
            files: [],
            isLoading: true,
            recentImage: null
        })
        this.loadImage(FILES[`image_${prefix}`])
    }

    loadImage = (files) => {
        setTimeout(() => {
            this.setState({
                files,
                isLoading: false
            }, () => {
                console.log(this.state.files[0])
            })
        }, 1000);
    }

    render() {
        const files = this.state.files.map(file => (
            <li key={file.name}>
                {file.name} - {file.size} bytes
            </li>
        ));
        return (

            <Container>

                <button
                    data-prefix="1"
                    onClick={(e) => this.handleClick(e)}
                    className="btn btn-primary">
                    Sample 1
                </button>
                <aside>
                    {files}
                </aside>

                <div className="img-fluid">
                    {this.state.files.length > 0 &&
                    <Image
                        src={URL.createObjectURL(this.state.files[0].image)}
                        height='400' rounded/>
                    }
                </div>
            </Container>


        )
    }
}

export default Classifier;