javascript 如何在react.js上设置默认图像

ppcbkaq5  于 2023-01-29  发布在  Java
关注(0)|答案(1)|浏览(157)

下面是product.js代码:

import { Button } from 'primereact/button';

const Product = ({product, onIncrement, onDecrement}) => {

    return(
        <div className='p-card border-white flex flex-column w-13rem  m-3'>
            <img src={`data:image/png;base64,${product.image}`} alt='img' className='border-round-sm h-9rem' />
            <div className='p-card-title flex flex-column align-items-center py-2 m-0'>
                <div>{product.name}</div>
                <div>€{product.price}</div>
            </div>
            <div className='p-card-content flex justify-content-center py-0'>
                <Button className="p-button-success m-1 px-3" onClick={()=>onIncrement(product)}>Aggiungi</Button>
                <Button className="p-button-danger m-1 px-3"  onClick={()=>onDecrement(product)}>Rimuovi</Button>      
            </div>      
            <div className='flex flex-column pt-2 pb-3'>
                <div className='flex justify-content-center'>Quantità: {product.quantity}</div>
                <div className='flex justify-content-center'>Totale: €{product.total}</div>
            </div>
        </div>
    );
    
}

export default Product;

下面是insertproductform.js代码:

import { useState , useRef, useContext } from "react";
import { InputText } from 'primereact/inputtext';
import {InputNumber} from 'primereact/inputnumber';

import axios from 'axios';

import { Toast } from 'primereact/toast';
import { InputTextarea } from 'primereact/inputtextarea';
import InsertProductImageForm from "./insertproductimageform";
import { Dialog } from "primereact/dialog";
import { Button } from "primereact/button";
import imagedefault from "../../../media/logo.png";
import { ContextProductList } from "../../store";

const Form = () => {

    const toast = useRef(null);
    const [visibleInsertImage, setVisibleInsertImage] = useState(false);
    const [productList, setProductList] = useContext(ContextProductList);
    

    const [name, setName] = useState('');
    const [price, setPrice] = useState(0);
    const [image, setImage] = useState(null);
    const [description, setDescription] = useState('');
    

    const setInputStateNull = () => {
        setName("");
        setPrice(0);
        setImage(null);
        setDescription("");
    
    }
   

    const handleSubmit = async (event) => {

        event.preventDefault();
        
       
        const product = {name, price, description};

        const formData = new FormData();
        formData.append('product', JSON.stringify(product));

        if(image === null){
            const imageDefault = new File([imagedefault], 'logo.png', { type: 'image/*' });
            formData.append('image', imageDefault);   
        } else {
            formData.append('image', image);
        }
        

        await axios.post("http://localhost:8080/product/addProduct", formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
                'Accept': 'application/json'
              
            },
            params: product,
            body : image
        }).then((response) => {
            setInputStateNull();
            if ( response.status === 200 ){
                response.data={...response.data, quantity:0, total: 0}
                setProductList([...productList, response.data]);

                toast.current.show({ severity: 'success', summary: 'Inserimento effettuato', detail: "Inserimento eseguito con successo.", life: 3000 });
            } else {
                const error = 'Inserimento fallito errore: ' + response.status;
                toast.current.show({ severity: 'error', summary: 'Inserimento fallito', detail: error, life: 3000 });
            }
        }).catch(() => {
            setInputStateNull();
            toast.current.show({ severity: 'error', summary: 'Inserimento fallito', detail: "Inserimento fallito errore generico.", life: 3000 });
        });
    }

    return(
        <>
           
           <form className='flex flex-column justify-content-center' onSubmit={handleSubmit}>
                
                
                <InputText value={name} onChange={(e) => setName(e.target.value)} placeholder="Nome" required />
                
                
                <InputNumber value={price} min="0" onValueChange={(e) => setPrice(e.target.value)} showButtons buttonLayout="horizontal"
                    decrementButtonClassName="p-button-danger"
                    placeholder="Inserire prezzo prodotto"
                    incrementButtonClassName="p-button-success"
                    incrementButtonIcon="pi pi-plus" 
                    decrementButtonIcon="pi pi-minus" 
                    mode="currency" 
                    currency="EUR"
                    step={0.25}
                   required

                />
                
                <InputTextarea id="descrizioneProdotto" value={description} onChange={(e) => setDescription(e.target.value)} required placeholder="Descrizione" />
                
                {
                    image !== null ?

                    <img src={image.objectURL} style={{alignSelf:"center"}} width="200" height="200" alt="Immagine"/>
                    :
                    <div style={{alignSelf:"center"}}>Inserire immagine</div>
                }
                <Button icon='pi pi-upload' style={{alignSelf:"center"}} className='p-button-rounded p-button-success' onClick={(event) => {event.preventDefault(); setVisibleInsertImage(true)}}/>
           
                <button type="submit">Inserisci</button>
                
            </form>
                
            <Toast ref={toast} />
            <Dialog className="w-6 h-30rem" header='Inserisci Immagine' draggable={false} visible={visibleInsertImage} onHide={()=> setVisibleInsertImage(false)}>
                <InsertProductImageForm onHide={()=> setVisibleInsertImage(false)} setImage={(e)=> setImage(e)}/>
                </Dialog>
                

        </>
    );
}

export default Form;

我想设置一个默认图像,在这种情况下logo.png,如果用户不把图像时,他插入一个新产品,它几乎工作,但它是这样的:On the left i inserted a product with an image and it works very well, on the right i inserted a new product without selecting an image, i think it catched the default image but it dosen't render it我怎么解决它?(我使用MongdoDB,而不是MySQL)
对不起,我的英语不好。

jjhzyzn0

jjhzyzn01#

您可以通过添加条件语句来设置默认图像,以检查产品图像是null还是空的。如果是,则将默认图像设置为src。以下是一个示例:

<img src={product.image ? `data:image/png;base64,${product.image}` : 'logo.png'} alt='img' className='border-round-sm h-9rem' />

此函数检查product.image是否为truthy,如果是,则将图像源设置为产品图像。如果是falsy,则将图像源设置为默认图像'logo.png'

相关问题