Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

290
Visualizações
Reaccionar: ¿cómo puedo obtener varios tamaños de imagen?

Tengo un objeto con enlaces.

 const urls = { small: https://image1.com, medium: https://image2.com, large: https://image3.com, };

la salida debería verse así:

 { small: {width: image_width, height: image_height}, medium: {width: image_width, height: image_height}, large: {width: image_width, height: image_height} }

Lo intenté así, pero resulta un bucle infinito. Ayúdame a arreglar mi función o muestra cómo es posible de otra manera

 const [imageSize, setImageSize] = useState({}); const getImageSize = () => { for (const url in urls) { const img = new Image(); img.src = urls[url]; img.onload = () => { setImageSize((prev) => { return { ...prev, [url]: { width: img.width, height: img.height, }, }; }); }; } };
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Para activar el oyente de onload de imágenes, debe montarse en el DOM; de lo contrario, no se llamará a setImageSize . Para hacer esto, debe tener imágenes válidas y adjuntarlas en algún lugar del html, así:

 const urls = { small: 'https://dummyimage.com/600x400/000/fff', medium: 'https://dummyimage.com/600x400/000/fff', large: 'https://dummyimage.com/600x400/000/fff', } const getImageSize = () => { for (const url in urls) { const img = new Image() img.src = urls[url] img.onload = () => { setImageSize(prev => { return { ...prev, [url]: { width: img.width, height: img.height, }, } }) } document.body.appendChild(img) } } useEffect(() => { getImageSize() }, [])
about 4 years ago · Juan Pablo Isaza Relatório

0

Pruebe este código a continuación:

 const [imageSize, setImageSize] = useState({}); const urls = { small: https://image1.com, medium: https://image2.com, large: https://image3.com, }; const getImageSize = () => { for (const size in urls) { var img = new Image(); img.onload = function() { setImageSize((prev) => { return { ...prev, [size]: {width: this.width, height: this.height} } }) }; img.src = url; } } useEffect(() => { getImageSize() }, [])
about 4 years ago · Juan Pablo Isaza Relatório

0

revisa el enlace del violín, espero que funcione[https://jsfiddle.net/k7bue0ho/][1]

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda