Django+DjangoRestFramework+React(TS):React-Image组件显示我的图像大小为1295×0

huangapple go评论67阅读模式
英文:

Django+DjangoRestFramework+React(TS): React-Image component showing my images' size as 1295x0

问题

在Django中,我有Group(组)、Class(类)、Model(模型)和Product(产品)作为模型。它们按照Group{Class{Model{Product}}}的层次结构排列。所以我创建了下拉框,它的工作方式如下所示:

  Group Checkbox
  |-Inner Classes of Selected Group
    |-Inner Models of Selected Class
      |-Inner Products of Selected Model
  (这里是<图片>元素)

Product模型具有一个图像字段,可以从response.json中成功返回。

我可以打开图像文件,例如http://localhost:8000/media/images/p1111.png。它的宽度小于1295像素,高度大于0像素,当然。

但是在网站上它不显示。

然后我打开Chrome DevTools。组件存在,组件的源代码中有<div><img>,但图像的大小显示为1295x0。我打开图像网址,它是类似256x256的尺寸。我可以(当然)使用CSS将图像宽度设置为500x500,但如果用户输入具有不同图像比例和尺寸的图像怎么办?这将使它看起来更糟糕,或者使图像只显示部分,所以这两种可能性都不好。那么,我是否可以通过更改React部分来解决这个问题?还是我需要在Django部分编写一个函数?

index.tsx:

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: 'they even banned shortened urls in TSX COMMMANDS? WTH???'
reportWebVitals();

App.tsx:

import React from "react";
import { Group, Class, Model, Product } from "./components/Group";
import './App.css';

function App() {
  return (
    <div className="App">
      <div className="App-header">
        <br/>
        <span className="header">The Main Page</span>
        <br/><br/>
        <Group />
        <Class />
        <Model />
        <Product />
      </div>
    </div>
  );
}

export default App;

components/Group.tsx:

// 以下省略...

希望这些信息对你有所帮助,如果你需要进一步的解决方案或有其他问题,请随时提出。

英文:

In Django; I have Group, Class, Model and Product as, well, models. These are in a hierarchy of Group{Class{Model{Product}}}. So I made dropdowns which works like:

  Group Checkbox
  |-Inner Classes of Selected Group
    |-Inner Models of Selected Class
      |-Inner Products of Selected Model
  (&lt;Image&gt; element here)

The Product models has an image field, which is returned succesfully from the response.json.

I can open the image files, e.g. http://localhost:8000/media/images/p1111.png. Its width is smaller than 1295px and its height is bigger than 0px, ofc.

But in website it does not show.

Then I open Chrome DevTools. Component is there, in component's source code &lt;div&gt;s and &lt;img&gt; are there, but image's size is shown as 1295x0. I open image url, it's smth like, 256x256. I can (of course) make image width 500x500 using CSS, but what if the use inputs an image with different image ratio and size? That will make it look worse or make the image show partially, so both possibilities are bad. So, can I solve it by changing the React part? Or I'm gonna write a function to Django part?

index.tsx:

import React from &#39;react&#39;;
import ReactDOM from &#39;react-dom/client&#39;;
import &#39;./index.css&#39;;
import App from &#39;./App&#39;;
import reportWebVitals from &#39;./reportWebVitals&#39;;

const root = ReactDOM.createRoot(
  document.getElementById(&#39;root&#39;) as HTMLElement
);
root.render(
  &lt;React.StrictMode&gt;
    &lt;App /&gt;
  &lt;/React.StrictMode&gt;
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: &#171;they even banned shortened urls in TSX COMMMANDS? WTH???&#187;
reportWebVitals();

App.tsx:

import React from &quot;react&quot;;
import { Group, Class, Model, Product } from &quot;./components/Group&quot;;
import &#39;./App.css&#39;;

function App() {
  return (
    &lt;div className=&quot;App&quot;&gt;
      &lt;div className=&quot;App-header&quot;&gt;
        &lt;br/&gt;
        &lt;span className=&quot;header&quot;&gt;The Main Page&lt;/span&gt;
        &lt;br/&gt;&lt;br/&gt;
        &lt;Group /&gt;
        &lt;Class /&gt;
        &lt;Model /&gt;
        &lt;Product /&gt;
      &lt;/div&gt;
    &lt;/div&gt;
  );
}

export default App;

components/Group.tsx:

import React,{useState,useEffect} from &quot;react&quot;;
import ReactDOM from &quot;react-dom&quot;
import {createRoot} from &quot;react-dom/client&quot;
import Select from &quot;react-select&quot;;
import {Image} from &quot;react-native&quot;

let GROUP:any=null
let CLASS:any=null
let MODEL:any=null

export function Group(props: {}){
    const [ groups, setGropus ] = useState&lt;any[]&gt;([]);
    const [ groupsel, setGroupSel ] = useState(&quot;0&quot;)
    GROUP=groupsel
    const serviceUrl = &#39;http://localhost:8000/app/groups/&#39;;

    let groupopt:any[]=[]
    groups.map((value:any)=&gt;{
      groupopt.push({value:value.id,label:value.groupName})
    })

    useEffect(()=&gt;{
        var myHeaders = new Headers();
        myHeaders.append(&quot;Content-Type&quot;, &quot;application/json&quot;);
        myHeaders.append(&quot;Authorization&quot;, &quot;Basic X19tZF9fOjE1OTk1MW15&quot;);

        var urlencoded = new URLSearchParams();
        urlencoded.append(&quot;groupName&quot;, &quot;Sample&quot;);

        var requestOptions:RequestInit = {
          method: &#39;GET&#39;,
          headers: myHeaders,
          redirect: &#39;follow&#39;
        };

        fetch(serviceUrl, requestOptions)
          .then(response =&gt; response.json())
          .then(result =&gt; setGropus(result))
          .catch(error =&gt; console.log(&#39;error&#39;, error));
    }, [])
    /*
    return (
        &lt;select id=&quot;group&quot; onChange={reloadAll}&gt;
          {
            groups.map((value:any) =&gt; {
                return (
                    &lt;option value={value.id} key={value.id}&gt;
                        {value.groupName}
                    &lt;/option&gt;
                )
            })
          }
        &lt;/select&gt;
    )
    */
   return (
    &lt;Select id=&quot;group&quot; defaultValue={groupopt[0]} options={groupopt} onChange={(event:any)=&gt;{setGroupSel(event?.value);}}&gt;&lt;/Select&gt;
   )
}

export function Class(props: {}){
    const [ classes, setClasses ] = useState&lt;any[]&gt;([]);
    const [ classsel, setClassSel ] = useState(&quot;0&quot;);
    const serviceUrl = &#39;http://localhost:8000/app/groups/&#39;+GROUP+&#39;/classes/&#39;;
    CLASS=classsel
    //console.log(GROUP)

    let classopt:any[]=[]
    classes.map((value:any)=&gt;{
      classopt.push({value:value.id,label:value.className})
    })

    useEffect(()=&gt;{
        var myHeaders = new Headers();
        myHeaders.append(&quot;Content-Type&quot;, &quot;application/json&quot;);
        myHeaders.append(&quot;Authorization&quot;, &quot;Basic X19tZF9fOjE1OTk1MW15&quot;);

        var urlencoded = new URLSearchParams();
        urlencoded.append(&quot;className&quot;, &quot;Sample&quot;);

        var requestOptions:RequestInit = {
          method: &#39;GET&#39;,
          headers: myHeaders,
          redirect: &#39;follow&#39;
        };

        fetch(serviceUrl, requestOptions)
          .then(response =&gt; response.json())
          .then(result =&gt; setClasses(result))
          .catch(error =&gt; console.log(&#39;error&#39;, error));
    }, [classes,classopt,classsel,classopt])
    /*
    return (
        &lt;select id=&quot;class&quot;&gt;
          {
            classes.map((value:any) =&gt; {
                return (
                    &lt;option value={value.id} key={value.id}&gt;
                        {value.className}
                    &lt;/option&gt;
                )
            })
          }
        &lt;/select&gt;
    )
    */
    return (
      &lt;Select id=&quot;class&quot; defaultValue={classopt[0]} options={classopt} onChange={(event:any)=&gt;{setClassSel(event.value);}}&gt;&lt;/Select&gt;
    )
}

export function Model(props: {}){
    const [ models, setModels ] = useState&lt;any[]&gt;([]);
    const [ modelsel, setModelSel ] = useState(&quot;0&quot;);
    const serviceUrl = &#39;http://localhost:8000/app/classes/&#39;+CLASS+&quot;/models/&quot;;
    MODEL=modelsel

    let modelopt:any[]=[]
    models.map((value:any)=&gt;{
      modelopt.push({value:value.id,label:value.modelName})
    })

    useEffect(()=&gt;{
        var myHeaders = new Headers();
        myHeaders.append(&quot;Content-Type&quot;, &quot;application/json&quot;);
        myHeaders.append(&quot;Authorization&quot;, &quot;Basic X19tZF9fOjE1OTk1MW15&quot;);

        var urlencoded = new URLSearchParams();
        urlencoded.append(&quot;modelName&quot;, &quot;Sample&quot;);

        var requestOptions:RequestInit = {
          method: &#39;GET&#39;,
          headers: myHeaders,
          redirect: &#39;follow&#39;
        };

        fetch(serviceUrl, requestOptions)
          .then(response =&gt; response.json())
          .then(result =&gt; setModels(result))
          .catch(error =&gt; console.log(&#39;error&#39;, error));
    }, [models,modelopt,modelsel,modelopt])
    /*
    return (
        &lt;select id=&quot;model&quot;&gt;
          {
            models.map((value:any) =&gt; {
                return (
                    &lt;option value={value.id} key={value.id}&gt;
                        {value.modelName}
                    &lt;/option&gt;
                )
            })
          }
        &lt;/select&gt;
    )
    */
    return (
      &lt;Select id=&quot;model&quot; defaultValue={modelopt[0]} options={modelopt} onChange={(event)=&gt;{setModelSel(event?.value);}}&gt;&lt;/Select&gt;
    )
}

export function Product(props: {}){
    const [ products, setProducts ] = useState&lt;any[]&gt;([]);
    const [ productsel, setProductSel ] = useState(&quot;0&quot;);
    const [ productimg, setProductImg ] = useState(&quot;http://localhost:8000/media/images/p1111.png&quot;);
    const serviceUrl = &#39;http://localhost:8000/app/models/&#39;+MODEL+&#39;/products/&#39;;

    let productopt:any[]=[]
    products.map((value:any)=&gt;{
      productopt.push({value:value.id,label:value.productName,trustedImg:value.trustedImg})
    })

    useEffect(()=&gt;{
        var myHeaders = new Headers();
        myHeaders.append(&quot;Content-Type&quot;, &quot;application/json&quot;);
        myHeaders.append(&quot;Authorization&quot;, &quot;Basic X19tZF9fOjE1OTk1MW15&quot;);

        var urlencoded = new URLSearchParams();
        urlencoded.append(&quot;productName&quot;, &quot;Sample&quot;);

        var requestOptions:RequestInit = {
          method: &#39;GET&#39;,
          headers: myHeaders,
          redirect: &#39;follow&#39;
        };

        fetch(serviceUrl, requestOptions)
          .then(response =&gt; response.json())
          .then(result =&gt; setProducts(result))
          .catch(error =&gt; console.log(&#39;error&#39;, error));
    }, [products,productopt,productsel,productimg])
    /*
    return (
        &lt;select id=&quot;product&quot;&gt;
          {
            products.map((value:any) =&gt; {
                return (
                    &lt;option value={value.id} key={value.id}&gt;
                        {value.productName}
                    &lt;/option&gt;
                )
            })
          }
        &lt;/select&gt;
    )
    */
    return (
      &lt;&gt;
        &lt;Select id=&quot;product&quot; defaultValue={productopt[0]} options={productopt} onChange={(event)=&gt;{setProductSel(event?.value);setProductImg(&quot;http://localhost:8000&quot;+event?.trustedImg)}}&gt;&lt;/Select&gt;
        &lt;Image id=&quot;image&quot; source={{uri:productimg}} style={{width:&quot;500px&quot;,height:&quot;500px&quot;}}/&gt;
      &lt;/&gt;
    )
}

/*
function reloadAll(){
  document.getElementById(&quot;group&quot;)?.remove()
  document.getElementById(&quot;class&quot;)?.remove()
  document.getElementById(&quot;model&quot;)?.remove()
  document.getElementById(&quot;product&quot;)?.remove()
  let root:any=createRoot(document.getElementsByTagName(&quot;header&quot;)[0])
  root.render(&lt;Group/&gt;)
  root.render(&lt;Class/&gt;)
  root.render(&lt;Model/&gt;)
  root.render(&lt;Product/&gt;)
}
*/

I tried with &lt;img&gt;, but it does not reload the image, so I'm using &lt;Image&gt; from react-image now. I tried width:500px,height:500px but we both know that this is a temporary and would not work if user adds another Product object with image.

So yeah. I thought "what you get in URL is what you get in Website", but again the frontend world seemed to fail me.

答案1

得分: 0

Welp, I was using react-native. That's why. It's a module for... mostly mobile devices. I put an instead and now it works.

英文:

Welp, I was using react-native. That's why. It's a module for... mostly mobile devices. I put an &lt;img&gt; instead and now it works.

huangapple
  • 本文由 发表于 2023年6月22日 14:35:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529141.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定