#image

질문 8
해시태그 없이 키워드만 일치하는 질문은 개수에 포함되지 않아요.

6달 전 · 노원재 님의 답변 업데이트

ReactNative ios build 에러 3일째 해결을 못했습니다.

시뮬레이션을 실행하려고 해도 스크립트 문제, iPhone 버전 범위 문제, 시뮬레이터 문제가 계속 발생합니다. 어떤 도움이라도 감사합니다. ReactNative를 처음 접했습니다. 저희 팀에서 저를 도울 수 있는 사람이 없습니다. #프로젝트 환경 mac M2 ruby -v ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin23] node -v v20.10.0 pod --version 1.15.2 package.json { "name": "labts", "version": "0.0.1", "private": true, "scripts": { "android": "react-native run-android", "ios": "react-native run-ios", "lint": "eslint .", "start": "react-native start", "test": "jest" }, "dependencies": { "@react-native-community/async-storage": "^1.12.1", "@react-native-community/cli": "13.6.9", "@react-navigation/bottom-tabs": "^6.6.0", "@react-navigation/native": "^6.1.17", "@react-navigation/native-stack": "^6.10.0", "@tanstack/react-query": "^5.51.5", "@types/react-native-vector-icons": "^6.4.18", "axios": "^1.7.2", "date-fns": "^3.6.0", "immer": "^10.1.1", "react": "18.2.0", "react-native": "0.74.3", "react-native-calendars": "^1.1305.0", "react-native-date-picker": "^5.0.4", "react-native-dotenv": "^3.4.11", "react-native-get-random-values": "^1.11.0", "react-native-image-crop-picker": "^0.41.2", "react-native-image-zoom-viewer": "^3.0.1", "react-native-paper": "^5.12.3", "react-native-permissions": "^4.1.5", "react-native-safe-area-context": "^4.10.8", "react-native-screens": "^3.32.0", "react-native-splash-screen": "^3.3.0", "react-native-tab-view": "^3.5.2", "react-native-vector-icons": "^10.1.0", "react-native-vision-camera": "^4.5.1", "uuid": "^10.0.0", "yarn": "^1.22.22" }, "devDependencies": { "@babel/core": "^7.20.0", "@babel/preset-env": "^7.20.0", "@babel/runtime": "^7.20.0", "@react-native/babel-preset": "0.74.85", "@react-native/eslint-config": "0.74.85", "@react-native/metro-config": "0.74.85", "@react-native/typescript-config": "0.74.85", "@types/react": "^18.2.6", "@types/react-native-dotenv": "^0.2.2", "@types/react-test-renderer": "^18.0.0", "babel-jest": "^29.6.3", "babel-plugin-module-resolver": "^5.0.2", "eslint": "^8.19.0", "jest": "^29.6.3", "prettier": "2.8.8", "react-test-renderer": "18.2.0", "typescript": "5.0.4" }, "engines": { "node": ">=18" } } PodFile require Pod::Executable.execute_command('node', ['-p', 'require.resolve( "react-native/scripts/react_native_pods.rb", {paths: [process.argv[1]]}, )', __dir__]).strip platform :ios, '12.0' use_frameworks! #use_modular_headers! prepare_react_native_project! linkage = ENV['USE_FRAMEWORKS'] if linkage != nil Pod::UI.puts "Configuring Pod with #{linkage}ally linked Frameworks".green use_frameworks! :linkage => linkage.to_sym end target 'nexlabts' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], # An absolute path to your application root. :app_path => "#{Pod::Config.instance.installation_root}/.." ) target 'nexlabtsTests' do inherit! :complete # Pods for testing end post_install do |installer| # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202 react_native_post_install( installer, config[:reactNativePath], :mac_catalyst_enabled => false, # :ccache_enabled => true ) end end 제가 아래 에러 3가지에 대해 제가 해본 방법들입니다. 1. node 재설치 node_module 폴더 삭제, package-rock.json 삭제 후 재설치 npm install --legacy-peer-deps yarn install 2. Xcode가 node 읽을 수 있도록 설정 sudo ln -s "$(which node)" /usr/local/bin/node 3. Podfile 내 platform 설정 수정 platform :ios, '12.0' or platform :ios, '14.0' 4. Pods 재설치 rm -rf ~/Library/Developer/Xcode/DerivedData or rm -rf ~/Library/Developer/Xcode/DerivedData/* rm -rf Pods rm Podfile.lock pod install --repo-update Xcode \> Product \> Clean Build Folder. cd ./ios pod cache clean -all pod install --repo-update cd ../ npx react-native run-ios --no-packager --simulator="iPhone 15" or npx react-native run-ios --simulator="iPhone 15" or yarn start > i(run ios) Err 1. cocoaPods 설치할 때 [!] CocoaPods could not find compatible versions for pod "React-RuntimeHermes": In Podfile: React-RuntimeHermes (from ../node_modules/react-native/ReactCommon/react/runtime) Specs satisfying the React-RuntimeHermes (from ../node_modules/react-native/ReactCommon/react/runtime) dependency were found, but they required a higher minimum deployment target. Err2. iOS 실행할때 run-ios --no-packager --simulator="iPhone 15" Build description signature: fc1341421f84b87c5245d346c2c17b66 Build description path: /Users/nowonjae/Library/Developer/Xcode/DerivedData/nexlabts-argvodqcybjfcybstpulfpghnzvm/Build/Intermediates.noindex/XCBuildData/fc1341421f84b87c5245d346c2c17b66.xcbuilddata /Users/nowonjae/Desktop/project/NeXLabRN/ios/nexlabts.xcodeproj:1:1: error: Unable to open base configuration reference file '/Users/nowonjae/Desktop/project/NeXLabRN/ios/Pods/Target Support Files/Pods-nexlabts/Pods-nexlabts.release.xcconfig'. (in target 'nexlabts' from project 'nexlabts') warning: Unable to read contents of XCFileList '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Unable to read contents of XCFileList '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-input-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-frameworks-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase 'Bundle React Native code and images' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase '[CP] Embed Pods Frameworks' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-input-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') error: Unable to load contents of file list: '/Target Support Files/Pods-nexlabts/Pods-nexlabts-resources-Release-output-files.xcfilelist' (in target 'nexlabts' from project 'nexlabts') warning: Run script build phase '[CP] Copy Pods Resources' will be run during every build because it does not specify any outputs. To address this warning, either add output dependencies to the script phase, or configure it to run in every build by unchecking "Based on dependency analysis" in the script phase. (in target 'nexlabts' from project 'nexlabts') --- xcodebuild: WARNING: Using the first of multiple matching destinations: { platform:iOS Simulator, id:B5AA2E84-4F83-4749-A986-A1FCE5E398A3, OS:17.5, name:iPhone 15 } { platform:iOS Simulator, id:B5AA2E84-4F83-4749-A986-A1FCE5E398A3, OS:17.5, name:iPhone 15 } ** BUILD FAILED ** ] Err3. Xcode 로 Build 할때 (Any iOS Simulator Device (arm64, x86_64)) Command PhaseScriptExecution failed with a nonzero exit code

개발자

#reactnative

#xcode

#reactnative-run-ios

답변 1

댓글 0

조회 427

2년 전 · 커리어리 AI 봇 님의 새로운 답변

리액트로 스프링과 웹소켓 채팅방을 구현했는데 자동 랜더링이 안됩니다..

안녕하세요! 현재 웹소켓으로 스프링과 채팅기능을 구현중에 있습니다 채팅방에서 채팅을 보내고 받는 건 가능한 상태인데 같이 채팅방에 입장해서 A가 B한테 보냈을 때 B가 페이지를 새로고침 하지 않으면 채팅이 자동 랜더링이 되지 않는 상황인데 여러 방법을 참고하고 해봤지만.. 성공하지 않았습니다 어떻게 풀어나가야 할지 잘 모르겠습니다 ㅠㅠ 코드가 길지만 ... 혹시 답변이 가능할까해서 참고해봅니다 좋은 키워드도 추천해주시면 감사하겠습니다!!... export const ChatRoomPage = () => { //메뉴 모달 const [isModalOpen, setIsModalOpen] = useState(false); const [isExitModalOpen, setIsExitModalOpen] = useState(false); const [backgroundPosition, setBackgroundPosition] = useState('static'); const location = useLocation(); const params = location.pathname; const segments = params.split('/'); const RoomUniqueId = segments[4]; const RoomId = segments[5]; const [messageData, setMessageData] = useState([]); const [messageList, setMessageList] = useState([]); const [message, setMessage] = useState(''); const accesskey = Cookies.get('Access_key'); // 채팅방 입장시 안내 문구 기능 const [showModal, setShowModal] = useState(false); const client = useRef({}); useEffect(() => { console.log('유즈이펙트 쉴행'); setShowModal(true); connect('L'); return () => disconnect(); }, []); const connect = type => { client.current = new StompJs.Client({ brokerURL: 'ws://222.102.175.141:8081/ws-stomp', connectHeaders: { Access_key: `Bearer ${accesskey}`, }, debug: function (str) { console.log('str ::', str); }, onConnect: () => { if (type === 'L') { subscribe(); publish(); } else { subscribe1(); publish1(); } }, }); client.current.webSocketFactory = function () { return new SockJS('http://222.102.175.141:8081/ws-stomp'); }; client.current.activate(); return () => disconnect(); }; const subscribe = () => { client.current.subscribe(`/sub/chat/messageList/${localStorage.memberUniqueId}`, message => { // console.log('messageData11 : ', JSON.parse(`${message.body}`)); setMessageData(JSON.parse(`${message.body}`)); const data = JSON.parse(`${message.body}`); setMessageList(data.data.chatMessageList); }); }; const publish = () => { client.current.publish({ destination: `/pub/chat/messageList/${localStorage.memberUniqueId}`, body: JSON.stringify({ chatRoomId: RoomId, chatRoomUniqueId: RoomUniqueId, page: 0, }), }); }; const closeModal = () => { setIsModalOpen(false); setBackgroundPosition('static'); }; const openModal = () => { setIsModalOpen(true); setBackgroundPosition('fixed'); }; const handleBackdropClick = e => { console.log('e ::', e); if (e.target === e.currentTarget) { closeModal(); } }; const ExitopenModal = () => { setIsExitModalOpen(true); }; const ExitcloseModal = () => { setIsExitModalOpen(false); }; const ReportButtonHandler = () => { alert('곧 업데이트 예정입니다!'); }; // 채팅 보내기 const sendMessage = message => { console.log('message :: ', message); connect(); setMessage(''); return () => disconnect(); }; const subscribe1 = () => { client.current.subscribe(`/sub/chat/message/${RoomUniqueId}`, message => { setMessageData({ ...messageList, message }); }); }; const publish1 = () => { client.current.publish({ destination: `/pub/chat/message/${RoomUniqueId}`, body: JSON.stringify({ memberId: `${localStorage.memberId}`, memberName: `${localStorage.memberName}`, memberUniqueId: `${localStorage.memberUniqueId}`, memberProfileImage: `${localStorage.profileImage}`, chatRoomId: RoomId, chatRoomUniqueId: RoomUniqueId, message: message, }), }); }; const disconnect = () => { client.current.deactivate(); }; console.log('messageList :: ', messageList); return ( <> <div style={{ width: '100%', height: '100%', position: backgroundPosition, }} > <Background> <Topbar> <Link to={`${PATH_URL.PARTY_CHAT}/${localStorage.memberUniqueId}`}> <TopBackDiv> <LeftBack /> </TopBackDiv> </Link> <TopbarName>모임이름</TopbarName> <ModalBtn onClick={() => { openModal(); }} > <RoomMenuIcon /> </ModalBtn> </Topbar> <Container> <Contents> <ParticipantDiv>ㅇㅇㅇ님이 참여했습니다.</ParticipantDiv> {messageList?.map((data, index) => { return ( <OtherDiv key={index}> <div style={{ position: 'relative', }} > <OtherImg> <OtherProfile> <img src={data.memberProfileImage} alt="profile" style={{ width: '100%', height: '100%', borderRadius: '8px', }} /> </OtherProfile> <OtherHostIcon> <PartHostIcon /> </OtherHostIcon> </OtherImg> <OthertInfo> <OtherName>{data.sender}</OtherName> <OtherContents> <OtherChatText>{data.message}</OtherChatText> <OtherChatTime>12:19 pm</OtherChatTime> </OtherContents> </OthertInfo> </div> </OtherDiv> ); })}

개발자

#채팅

#웹소켓

#채팅기능

답변 2

댓글 0

조회 594

일 년 전 · 익명 님의 질문 업데이트

api의 첫번째 호출 이후부터 antd Button 렌더링 안되는 이슈가 있습니다.

```jsx import { Popover, Modal, Button, Image, Result } from "antd"; const [prevImg, setPrevImg] = useState(["any"]); const [loading, setLoading] = useState(false); const [removeImgFiles, setRemoveImgFiles] = useState([]); const combinePrevImages = (prevImages, newImages) => { const combinedImages = [...prevImages, ...newImages]; return combinedImages; }; useEffect(() => { const postSeg = async () => { try { const res = await axios.post( "apiurl", { filepath: filePath, clips: sortableList.map(list => `${list.seg.start}-${list.seg.end}`), frame: frameValue }, { proxy: false } ); return res.data; } catch (error) { console.error("Error posting segments:", error); return []; } finally { setLoading(false); } }; const postSegments = async () => { if (segments[0]?.start === 0 && segments[0]?.end === 0) return; if (sortableList && filePath) { setLoading(true); const res = await postSeg(); const combinedPrevImg = combinePrevImages(prevImg, res.results); setPrevImg(combinedPrevImg); console.log("Post Request Success"); } }; postSegments(); }, [filePath, segments, frameValue]); const handleModalOpen = useCallback(() => setModalOpen(true), []); const handleModalClose = useCallback(() => { setRemoveImgFiles([]); setModalOpen(false); }, []); const handleDeleteButtonClick = async () => { if (removeImgFiles.length > 0) { setPrevImg([...removeImgFiles]); setRemoveImgFiles([]); } else { const result = await showSwal({ title: "Are you sure delete?", showCancelButton: true, confirmButtonText: "Confirm", cancelButtonText: "Cancel", confirmButtonColor: "#3085d6", cancelButtonColor: "#d33" }); if (result.isConfirmed) { setRemoveImgFiles([...prevImg]); setPrevImg([]); } const success = await Promise.all(removeImgFiles.map(deleteFiles)); return success; } } const handleRemoveFinish = async () => { if (removeImgFiles) { for (const filePath of removeImgFiles) { try { await removeFile(filePath); } catch (e) { console.log("File Remove Error", e); } } } setRemoveImgFiles([]); handleModalClose(); }; return ( <motion.div initial={{ x: width }} animate={{ x: 0 }} exit={{ x: width }} transition={mySpring} > <div style={{ fontSize: 12, padding: "0 5px", color: "var(--gray12)", display: "flex", justifyContent: "space-between", alignItems: "center" }} > <FaAngleRight title={t("Close sidebar")} size={20} className="angle-right" role="button" onClick={toggleSegmentsList} /> {header} <FaExpandArrowsAlt title={t("Image Inspection")} size={18} className="expand-arrow-alt" style={{ cursor: "pointer" }} role="button" onClick={!loading ? handleModalOpen : handleModalClose} /> <Modal title={t("Image Inspection")} centered onCancel={handleModalClose} open={modalOpen} footer={[]} width="100%" > <div className="imagecontainer"> <Button danger className="toggle-remove" onClick={handleDeleteButtonClick}> {removeImgFiles.length > 0 ? "Add" : "Remove"} </Button> {prevImg?.length > 10 && prevImg.map(img => ( <Popover key={img}> {removeImgFiles?.includes(img) ? ( <span> <Result className="result" icon={<FaSmile />} subTitle="delete" /> </span> ) : <Image key={uuidv4()} src={img} preview={{ src: img }} alt={uuidv4()} /> )} </Popover> ))} </div> <Button block onClick={handleRemoveFinish}> Finish </Button> </Modal> </div> ) ``` api 호출을 통해 frameValue 개수(여기서는 12개씩) 만큼 이미지를 렌더링 하고 있는데 두번째 호출부터는 Button이 렌더링되지 않아서 어디가 잘못됐는지 알고싶습니다.. 필요한 부분이 imagecontainer 클래스네임인 div를 렌더링 해야합니다.

개발자

#react

답변 0

댓글 0

조회 81

일 년 전 · 민경배 님의 답변 업데이트

리액트 내비게이션 초기 데이터값 설정

import React, { useEffect, useState } from "react"; import { Link, useLocation } from "react-router-dom"; import { TbArrowBigUpFilled } from "react-icons/tb"; import useScroll from "../utils/useScroll"; import useProductsQuery from "../useProductsQuery"; const Nav = () => { const { isNavFixed } = useScroll(); const [activeButton, setActiveButton] = useState(0); const handleButtonClick = (index) => { setActiveButton(index); }; const categoryNames = { materials: "소재별 품목", purposes: "용도별 품목", }; const [isScrollMenuVisible, setScrollMenuVisible] = useState(false); const handleMouseEnter = () => { setScrollMenuVisible(true); }; const handleMouseLeave = () => { // console.log("마우스 이탈"); setScrollMenuVisible(false); }; const location = useLocation(); const isloginorsignup = location.pathname === "/login" || location.pathname === "/signup"; const { isLoading, isError, errorMessage, materials, purposes } = useProductsQuery(); const [hoveredOnedepth, setHoveredOnedepth] = useState(null); const [onedepthChildren, setOnedepthChildren] = useState([]); const [hoveredDivision, setHoveredDivision] = useState(null); const [twodepthDivision, setTwodepthDivision] = useState([]); const handleOnedepthMouseEnter = (item) => { setHoveredOnedepth(item); // console.log(setHoveredOnedepth) setOnedepthChildren(item.children); }; const handletwodepthMouseEnter = (child) => { setHoveredDivision(child); // console.log(setTwodepthDivision); setTwodepthDivision(child.divisions); // console.log(child.divisions); }; if (isLoading) return <>로딩 중...</>; if (isError) return <>{errorMessage}</>; return ( <> {!isloginorsignup ? ( <> {/* 대메뉴 */} <nav id="nav" className={`nav ${isNavFixed ? "fixed" : ""}`}> <div className="nav_wrap"> <div className="twobutton_wrap"> {["materials", "purposes"].map((category, index) => ( <Link type="button" className={`twobutton ${ activeButton === index ? "active" : "" }`} key={index} onClick={() => handleButtonClick(index)} to={`/${category}`} > {categoryNames[category]} </Link> ))} </div> {/* 내비게이션 1depth */} <div className="scrollnav"> <ul className="materialnav" style={{ display: activeButton === 0 ? "flex" : "none", }} > {materials.map((material) => ( <li key={material.id} className="materialnav_li" onMouseEnter={() => { handleOnedepthMouseEnter(material); handleMouseEnter(); }} onMouseLeave={handleMouseLeave} > <Link to="/">{material.name}</Link> </li> ))} </ul> <ul className="usagenav" style={{ display: activeButton === 1 ? "flex" : "none", }} > {purposes.map((purpose) => ( <li key={purpose.id} className="usagenav_li" onMouseEnter={() => { handleOnedepthMouseEnter(purpose); handleMouseEnter(); }} onMouseLeave={handleMouseLeave} > <Link to="/">{purpose.name}</Link> </li> ))} </ul> </div> <div className="call_wrap"> <div className="call"> <div className="call_title">견적 상담 · 문의 대표전화</div> <div className="top_button"> <TbArrowBigUpFilled className="top_icon" /> <p>TOP</p> </div> </div> </div> </div> </nav> {/* 2&3depth 호버 메뉴 */} <div className={`scrollmenu ${isScrollMenuVisible ? "show" : ""} ${ isNavFixed ? "fixed" : "" }`} style={{ visibility: isScrollMenuVisible ? "visible" : "hidden" }} onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} > {activeButton === 0 && ( <div className="scrollmenu_top"> <ul className="depth2_wrap"> {onedepthChildren.map((child) => ( <li key={child.id} className="depth2_menu" onMouseEnter={() => { handletwodepthMouseEnter(child); }} > <div className="depth2_menu_img_wrap"> <div className="depth2_menu_img"> <img src={child.images[0]._links.href} alt={child.name} /> </div> </div> <p>{child.name}</p> </li> ))} </ul> </div> )} <div className="scrollmenu_middle"> <div className="depth3_wrap"> {twodepthDivision.map((division) => ( <Link key={division.id} to="/" className="depth3_menu"> <span className="depth3_menu_img"> {/* images 속성이 없거나 비어 있어도 오류를 방지 */} {division.images && division.images.length > 0 && ( <img src={division.images[0]._links.href} alt={division.division_name} /> )} </span> <p>{division.division_name}</p> </Link> ))} </div> </div> <div className="scrollmenu_bottom"></div> </div> </> ) : null} </> ); }; export default Nav; 현재는 depth2_menu 호버해야만 depth3_menu가 보이는데 초기에 scrollmenu가 보일때부터 depth2_menu가 (onedepthChildren.map의 첫번째 순서의 데이터가) 호버되어있어 그에 매칭되는 division의 내용들이 depth3_menu에 보이게 할수있는 방법 있을까요 ?

개발자

#react

답변 1

댓글 0

조회 113

<input type="file" multiple> 관련하여..

<template> <div> <input ref="fileInput" type="file" accept="image/*" multiple="true" @change="handleFileInputChange" /> <button @click="openFileInput" class="select-button"> Select Images </button> <div class="preview-container"> <div v-for="file in selectedFiles" :key="file.lastModified" class="preview-item" > <p>{{ file.name }}</p> <div class="preview"> <img :src="previewImage" style="width: 100px" /> </div> <!-- <img :src="URL.createObjectURL(file)" /> --> <button @click="removeFile(file.lastModified)" class="remove-button"> X </button> </div> </div> </div> </template> <script setup lang=“ts”> const fileInput = ref() const selectedFiles: Ref<Array<any>> = ref([]) const openFileInput = () => { fileInput.value.click() } const previewImage = ref<any>('') const handleFileInputChange = e => { // const files = Array.from(fileInput.value.files) const files = e.target.files console.log('files', files) selectedFiles.value.push(...files) console.log('add selectedFiles', selectedFiles.value) for (let i = 0; i < selectedFiles.value.length; i++) { const file = selectedFiles.value[i] console.log('handleFileInputChange_ file', selectedFiles.value[i]) const reader = new FileReader() reader.onload = e => { previewImage.value = e.target.result } reader.readAsDataURL(file) } } const removeFile = lastModified => { selectedFiles.value = selectedFiles.value.filter( file => file.lastModified !== lastModified ) console.log('remove selectedFiles', selectedFiles.value) } </script> 모바일에서 카메라로 찍은 여러장의 사진들이 각각의 썸네일로 노출되어야함 현재는 최신 사진으로 엎어치기 됨.. 예) 'A B C D' 의 사진이 나와야하는데 현재는 A 찍고 B찍으면 'B B' 가 됨 C찍으면 'C C C'가 됨 도와주세요!

개발자

#input

#type='file'

#vue3

#multiple

#preview

답변 3

댓글 0

보충이 필요해요 1

조회 170

input type="file" 사용법

<template> ...(생략) <label for="camera" class="btn btn-purple btn-square btn-lg col-6 right-border" v-if=" imageYn === 'N' && imageYn === null" > 사진 촬영 </label> //class가 조건에 따라 달라짐. <label for="camera" class="btn btn-secondary btn-square btn-lg col-6 right-border" v-if=" imageYn === 'Y' " > 사진 촬영 </label> <input type="file" id="camera" accept="image/*" capture="camera" style="display: none" @change="onFileSelected" /> <button class="btn btn-secondary btn-square btn-lg col-6 left-border" @click="rightButton" v-if="status === '방전 시작'" > 방전 완료 </button> ...(생략) </template> <script setup lang="ts"> const imageYn:string = ref('') console.log('2', imageYn.value) //사진촬영 const onFileSelected = event => { const file = event.target.files[0] if (file) { imageYn.value = 'Y' console.log('1') console.log('imageYn', imageYn.value) console.log('yes file', file) } else { imageYn.value = 'N' console.log('imageYn', imageYn.value) console.log('no image') } } </script> 결과 사진 찍기 전 -> imageYn ='N' 이거나 null일 경우-> class에 btn-purple 적용 카메라를 실행하여 사진을 찍었을 경우 -> imageYn='Y' -> class에 btn-secondary 적용 / disable처리도 되야함 문제점 사진촬영 후 console 1번은 'Y' 찍히되 2번엔 null입니다. 도와주세요!

개발자

#자바스크립트

#vue3

#compositionapi

#input

#type="file"

답변 1

댓글 0

조회 358

3달 전 · 익명 님의 새로운 댓글

자바스크립트의 이벤트 처리 질문

리액트로 이미지 inpainting 컴포넌트를 만들고 있습니다. 사용자가 이미지 업로드를 하면 canvas 영역에 그 이미지가 채워지고 그 이미지에 mask 영역을 칠할 수 있는 이미지 에디터 컴포넌트인데요, 궁금한게 생겨 질문드립니다. 첨부한 코드는 컴포넌트의 코드중 이미지 업로드 시 onChange 이벤트의 처리기인 handleImageUpload 함수와, handleImageUpload 함수에서 호출되는 loadImage 함수의 코드입니다. 사용자가 input 요소에 이미지를 업로드하면 onChange 이벤트가 발생해 handleImageUpload 함수가 실행되고 loadImage 함수가 실행됩니다. loadImage 함수가 실행되면 img 객체가 생성되고 img 객체의 src를 지정하죠. 그러면 브라우저는 이미지 로딩을 시작하고 이미지 로딩이 완료되면 onload 콜백함수가 실행됩니다. 저는 이 과정을 자바스크립트의 콜스택, 이벤트 루프, 태스크큐 구조에서 나타내보자면 다음과 같다고 생각했습니다. 1. 초기상태 콜스택 : [ ] 태스크큐 : [ ] 2. 사용자가 파일을 업로드 -> onChange 이벤트 발생 콜스택 : [handleImageUpload] 태스크큐 : [ ] 3. handleImageUpload 내부에서 loadImage 함수 호출 콜스택 : [handleImageUpload, loadImage] 태스크큐 : [ ] 4. loadImage 내부에서 img 객체 생성 및 src 할당 콜스택 : [handleImageUpload, loadImage] 태스크큐 : [ ] Web API : 이미지 로딩 시작 5. loadImage 함수 종료, handleImageUpload 함수 종료 콜스택 : [ ] 태스크큐 : [ ] Web API : 이미지 로딩 진행중 6. 이미지 로딩이 완료되면 Web API가 onload 콜백을 태스크큐에 추가 콜스택 : [ ] 태스크큐 : [onload] Web API : 이미지 로딩 완료 7. 이벤트 루프가 콜스택이 비어있음을 확인하고 태스크큐에서 onload 콜백을 콜스택으로 이동 콜스택 : [onload] 태스크큐 : [ ] 8. onload 콜백 실행 (캔버스에 이미지 그리기 등) 콜 스택 : [onload, drawImage, ...] 태스크큐 : [ ] 일단 이 과정이 맞나요? 만약 이게 맞다면 생기는 궁금증이 있습니다. Web API에서 이미지 로딩이 진행되는동안 loadImage 함수 및 handleImageUpload 함수가 종료되면 loadImage 함수 내에서 생성된 img 객체는 가비지 컬렉터에 의해 지워져야 하지 않나? 그렇게 img 객체가 GC에 의해 사라지면 이미지 로딩이 완료되었을 시점엔 img 객체의 onload 함수도 없어진것이니 onload 함수의 로직은 실행이 되지 않아야 하는 거 아닌가? 하는 생각이 들어 질문드립니다

개발자

#자바스크립트

#react

#frontend

답변 1

댓글 1

조회 249

<input type="file"> 관련하여..

<template> <label for="camera1"> 촬영 </label> <input type="file" id="camera1" accept="image/*" capture="camera" style="display: none" @change="onStartFileSelected" /> </template> <script> const startFile = ref({}) //@change const onStartFileSelected = event => { const startFileInfo = event.target.files[0] startFile.value = startFileInfo if (startFileInfo) { startImageYn.value = 'Y' console.log('startFileInfo', typeof startFileInfo) } else { startImageYn.value = ' ' console.log('no image') } } // 파일 포함 다음 상태 업데이트하는 api const fileUpdateStatusApiHandler = async () => { const formData = new FormData() console.log('startFile===',startFile.value)//File형식 데이터 정상 찍힘 -> 타입 : 객체(Object) console.log('startFile',JSON.stringify(startFile.value)) //안찍힘???왜?????? 객체->스트링으로 바꿈 formData.append('file_upload', JSON.stringify(startFile.value),startFile.value) //빈값이 들어감.. try { const res: any = await ApiCert.post( API_URL.url, formData, { headers: { 'Content-Type': 'multipart/form-data' } } ) console.log('response =====', res) if (res.resCode === 'OK') { console.log('OK') } else { alert(res.resMsg) } } catch (err: any) { console.log('error =====', err) } } </script> file형식 데이터를 api보낼때 formData에 넣어 보내고싶은데 file이 안들어가네요.. file_upload: {} 빈값으로 들어갑니다. 도와주세용

개발자

#input

#type="file"

#vue3

#javascript

#form-data

답변 2

댓글 0

조회 180

2년 전 · 김현진 님의 답변 업데이트

onChange 함수 관련하여

<template v-for="(item, i) in checkListItem" :key="i"> <label for="camera"> <form> <input type="file" id="camera" accept="image/*" style="display: none" @change="e => handleFileInputChange(e, i, item)" /> </form> </label> </template> <script lang=“ts” setup> const handleFileInputChange = (e, i, item) => { console.log(checkListItem.value) //콘솔1 console.log(item) //콘솔2 console.log(i) //콘솔3 const files = e.target.files[0] const reader = new FileReader() reader.onload = e => { /* 수정필요 */ item[i].check_file = e.target.result item[i].checked = true } reader.readAsDataURL(files) } <script> //콘솔1 checkListItem = [ {checkId: 11, content: ‘체크리스트1’}, {checkId: 12, content: ‘체크리스트2’}, {checkId: 13, content: ‘체크리스트3’}, {checkId: 14, content: ‘체크리스트4’}, {checkId: 15, content: ‘체크리스트5’} ] handleFileInputChange 함수 실행 시 선택한 checkListItem의 item과 index값을 가져와 선택한 item에 파일 첨부하고싶은데.. 현재는 체크리스트4번에 파일을 첨부하면 체크리스트1에 값이 들어옵니다. 콘솔 찍어보면 무조건 첫번째 객체값 부터 찍힙니다. //콘솔2 는 {checkId: 11, content: ‘체크리스트1’}, //콘솔3은 0 이 찍힙니다.

개발자

#onchange

#javascript

#vue3

답변 2

댓글 0

조회 77

9달 전 · 백승훈 님의 새로운 답변

react-query로 이미지를 가져올 때, 이미지가 깜빡거리는 문제를 해결하고 싶어요.

React 프로젝트에서 차량 데이터 목록(차량 모델 사진, 차량명, ....등)을 보여주는 웹 프로젝트를 진행하고 있습니다. 차량 데이터 목록 화면에서 react-query를 통해 가져온 데이터는 (예시 데이터) const data = [{id: number, car_name: string, model_name, car_model_image: number...}, {.....} ] 이런식으로 가져와서 map을 통해 CarCard 컴포넌트에 데이터를 props로 보내어 현재 출력하고 있습니다. 여기서 이미지 같은 경우는 백엔드에서 차량 모델 이미지를 가져오는 api를 따로 만들어놓아서, props로 전달받은 car_model_image 즉, 차량 모델 이미지의 id를 통해서 차량 모델 이미지 api에 데이터를 요청해서 이미지를 출력하고 있습니다. 이때. 페이지를 전환하거나, 한 페이지에서 아무동작을 하지 않아도 게속 이미지가 깜빡거리면서 재렌더링이 되고, 계속 무한정으로 이미지를 호출하는 문제가 발생하였습니다. map을 통해 CarCard를 호출하고 CarCard 안에서 이미지를 호출함에 따라서 계속 이미지가 깜빡깜빡 거리는 것 같은데, 컴포넌트 안에서 이미지를 호출할 때 어떻게 하면 무한정으로 이미지를 불러오지 않도록 하고 깜빡거림을 없앨 수 있을까요 ?...어떻게 해결해야 할지 감이 안 잡혀요.... //차량 목록 페이지 한 부분 ... const { data } = useGetCarList(); //useQuery를 통해 서버에서 데이터 전달받음 // const data = [{id: number, car_name: string, model_name, car_model_image: number...}, {.....} ] 이런식 .... return ( <div> data.map((data: CarData) => { return ( <Carcard ascCarData={data} key={Math.random()} handleClick={() => handleClick(data)} isActive={true} /> ); }) </div> ) //Carcard 컴포넌트 const { data: carImage } = useGetCarModeImage(ascCarData.car_model_image); // 이미지 데이터 가져오기

개발자

#react

#vite

#react-query

#typescript

#react-query-v3

답변 4

댓글 0

조회 301

일 년 전 · 이상선 님의 새로운 답변

Async await fetch 오류

const Content: React.FC = () => { const [htmlContent, setHtmlContent] = useState<string>(''); const data = { "filePath": ""https://cdn-image-dev.test.io/dev/contents/terms/2023/10/11/",", "fileName": "test.html" } const url = `${data.filePath}${data.fileName}`; // HTML 파일 가져오기 const fetchHtmlFile = async () => { try { const res = await fetch(url); console.log('res', res); if (res.ok) { const html = await res.text(); setHtmlContent(html); } else { console.error('Failed to fetch HTML file'); } } catch (error) { console.error('Error fetching HTML file:', error); } }; fetchHtmlFile(); return( <div dangerouslySetInnerHTML={{ __html: htmlContent }} /> ) } fetchHtmlFile 호출 시켜 res에서 얻은 html소스를 가져와 htmlContent에 넣어야하는데 에러나네요,, **에러메세지 Content.tsx:30 Error fetching HTML file: TypeError: Failed to fetch Cors 오류 참고 -- api url : https://api-dev.test.io/api/test/v1/~~ 도와주세요!

개발자

#react

#html

#async

#fetch

답변 1

댓글 0

조회 94

react에서 axios, map 함수를 통한 api 호출

api를 axios를 통해 불러와서 map 함수로 뿌려주려고 합니다. 다음과 같은 api 형태이구요(이미지 url은 익명글이기 때문에 가짜로 넣었습니다) { isSuccess: true, code: 1000, message: "요청에 성공하였습니다.", result: [ { bannerIdx: 1, bannerImgUrl: "https://abcde.png", bannerTitle: "프리온보딩", bannerContent: "실무에서 사용할 수 있나요?" }, ] } 이 api를 다음과 같은 함수형 컴포넌트로 호출하는데 불러와지지가 않습니다. 아래 url은 제가 제 정보보호를 위해 가짜로 넣어놓았구요. console에는 정상적으로 api 내용이 출력되고는 있습니다. 그런데 화면에 표시가 안됩니다. 왜 안될까요? function TopBanner() { const [bannerData, setBannerData] = useState([]); useEffect(() => { getBannerData(); }); const getBannerData = async () => { const result = await axios({ method: "GET", url: "https://abcde/abc/abc", }).then((response) => { console.log(response.data); setBannerData(response.data.result); }); setBannerData(result); }; return ( <Base> <Container> <StyledSlider {...settings}> {bannerData && bannerData.map((banner) => ( <div className="slick-slide"> <div key={banner.data.result.bannerIdx} imgUrls={banner.data.result.bannerImgUrl} alt={banner.data.result.bannerTitle} className="banner-image" /> </div> ))} </StyledSlider> </Container> </Base> ); } export default TopBanner;

개발자

#react

답변 2

댓글 0

추천해요 1

조회 1,307

[SwiftUI]array에 값이 append 되질 않아요

코드 실행은 되는데 만든 plus버튼을 눌러서 AddFile함수를 실행시켜도 folders어레이에 아무 값이 추가 되질 않아요ㅠ AddFile함수를 잘못 작성한 것일까요? 코드는 전체 복붙해놨습니다 import SwiftUI struct Category: View { var body: some View { NavigationView { ScrollView { VStack { HStack { Text("Category") .font(.title) .padding(.horizontal) Spacer() Button { AddFile(title: "hello") } label: { Image(systemName: "plus") .font(.title2) .padding(.horizontal) } } Text("\(folders.count)") if folders.first != nil { ForEach(folders) { folder in ZStack { RoundedRectangle(cornerRadius: 15) .frame(width: 100, height: 100) .foregroundColor(.yellow) Text(folder.title) .font(.title3) .fontWeight(.bold) } } } else { Text("No folder") } } } } } func AddFile(title: String) { folders.append(Folder(title: title)) } } struct Folder: Identifiable { var id = UUID().uuidString var title: String } var folders: [Folder] = [ Folder(title: "hi"), Folder(title: "hello") ] struct Category_Previews: PreviewProvider { static var previews: some View { Category() } }

개발자

#swift

#swiftui

#append

#array

답변 1

댓글 0

추천해요 1

조회 209

일 년 전 · 이상선 님의 새로운 답변

Lighthouse를 이용한 성능 최적화 - 텍스트 압축 사용

안녕하세요. 개발한 웹 페이지를 lighthouse를 통해 성능 최적화에서 난관을 겪고 1년차 React 개발자입니다. lighthouse에서 추천 항목에 "텍스트 압축 사용"을 적용해보려 시도 중입니다. .htaccess 파일에 다음과 같은 코드를 넣어서 텍스트 압축을 실행하였습니다. <IfModule mod_deflate.c> AddOutputFilterByType DEFLATE image/svg+xml AddOutputFilterByType DEFLATE text/plain AddOutputFilterByType DEFLATE text/html AddOutputFilterByType DEFLATE text/xml AddOutputFilterByType DEFLATE text/css AddOutputFilterByType DEFLATE application/xml AddOutputFilterByType DEFLATE application/xhtml+xml AddOutputFilterByType DEFLATE application/rss+xml AddOutputFilterByType DEFLATE application/javascript AddOutputFilterByType DEFLATE application/x-javascript AddOutputFilterByType DEFLATE application/x-font-ttf AddOutputFilterByType DEFLATE application/vnd.ms-fontobject AddOutputFilterByType DEFLATE font/opentype font/ttf font/eot font/otf </IfModule> 결과적으로 네트워크 탭에서 Content-Encoding: gzip 으로 표시되는 것을 보니까, 텍스트 압축이 되는 것처럼 보입니다. 그런데 lighthouse에서는 성능 점수가 더 올라가지 않고 있습니다. 혹시 "텍스트 압축" 부분에서 최적화 하는 다른 방법이 있을까요? 아니면 제가 놓치고 있는 부분이 있는 걸까요?

개발자

#react

#lighthouse

#front-end

답변 1

댓글 0

조회 310

9달 전 · 그린티라떼 님의 답변 업데이트

react에서 복잡한 상태를 관리할때.. 한번에 관리? 분리해서 관리? (jotai, recoil, useState)

안녕하세요 react를 이용해서 복잡한 작성 페이지를 만들고있습니다. 아래의 타입은 예시입니다. type payload = { name: string; message: string; type: string; url: { pc: string; mobile: string; }; contents: { images: { url: string; name: string; }[]; buttons: { name: string; url: string; }[]; }; conditions: { ... }, .... }; 위처럼 복잡한 데이터를 서버로 보내줘야해서 데이터를 관리해야하는데 현재는 페이지내에 구조가 복잡하고 컴포넌트도 매우많아 props drilling이 너무 심해질거같아서 recoil, jotai와 같은 상태관리 라이브러리를 이용해서 작업을 진행하고있습니다. 이러한 상황에서 관리하는 데이터를 한객체에 모아서 관리하는게 좋은지 아니면 const nameAtom = atom(''); const messageAtom = atom(''); const typeAtom = atom(''); const urlAtom = atom({ pc: '', mobile: ''}); .... 처럼 일일히 쪼개서 관리하는게 맞는 방향인지 모르겠어서 질문드립니다 ! (사수가없어서 물어볼곳이없어요...) 현재는 아래와같이 쪼개서 작업한뒤 submit시에 합쳐주는 방식으로 구현해놓았는데 atom 갯수가 20개 정도 되버리니까 너무 복잡해보여서 이게맞나... 싶어서 질문드리게되었습니다.

개발자

#react

#frontend

답변 2

댓글 0

보충이 필요해요 1

조회 218

django 정적 이미지 업로드 질문드립니다

제가 venvs/mysite/pybo/templates 안의 hello.html 파일 안에 {%load static} 하고 venvs/mysite/pybo/static/image 이 폴더에 있는 이미지 를 불러오기 하려고 <img src={%static '/django.jpg' %}> 이걸 하는데 계속 이미지는 안뜨고 css 파일만 뜨네요 ㅠㅠㅠ django.jpg는 이미지이름입니다 config 파일 내에 settings 안에서도 STATIC_URL = "/static/" STATICFILES_DIRS = [ os.path.join(BASE_DIR,"pybo/static") ] 이것도 했는데 안되네요 ㅠㅠㅠㅠ pybo/view.py 파일 안에도 from django.shortcuts import render,get_object_or_404,redirect from django.http import HttpResponse from .models import Question,Answer def hello(request): #return HttpResponse('pybo/hello.html') return render(request,'pybo/hello.html') 뭐가 문제인걸까요 ... 파이썬 migrate랑 runserver도 다 새로고침 했습니다..

개발자

#디장고

#django

#프레임워크

#장고

#백엔드개발

답변 1

댓글 0

조회 97

객체 배열에 대해서 컴포넌트를 어떻게 설계하시나요??

안녕하세요. 객체배열에 대해서 컴포넌트를 여러분은 어떻게 제작하고 계실까요?? 처음에는 첫번째 처럼 컴포넌트를 제작하다가 다른 곳에서도 재활용 할수있는 컴포넌트가 좋을것같아서 두번째 코드처럼 설계를 했는데 단점이 이중 for문을 쓰게 되는것 입니다… 제머리로는 더 깊게는 생각이 안나서 혹시 다른방법을 사용하고 계신분이 계실까요?? 첫번째(정적인 설계) function example() { const object = [ { id: 1, age: 17, name: 'strict' }, { id: 2, age: 16, name: '"love"' } ] return ( <> {object.map((item, index) => ( <div key={item.id}> {item.age} {item.name} </div> ))} </> ) } 두번째(동적인 설계) function example() { const object = [ { id: 1, number: 17, title: 'strict' }, { id: 2, number: 16, title: 'love' } ] const object2 = [ { id: 1, age: 17, name: 'strict' }, { id: 2, age: 16, name: 'love' } ] const value1 = ['number', 'title'] const value2 = ['age', 'name'] const TwoFor = ({obj, value}) => obj.map((item) => value.map((v) => { return <div>{item[v]}</div> }) ) return ( <> <TwoFor obj={object} value={value1} /> <TwoFor obj={object2} value={value2} /> </> ) }

개발자

#react

#객체배열

#컴포넌트

답변 1

댓글 1

조회 190

7달 전 · 아기 개발자 님의 새로운 답변

Yolov8 모델 저장

안녕하세요 Vscode에서 train폴더에서 model = YOLO("yolov8m.pt") # GPU설정 model = model.to(device) model.train(data='data.yaml', epochs=5) torch.save(model.state_dict(), 'yolov8m_trained.pt') 다음과 같이 모델을 학습 시킨후 Predict폴더에서 # 모델 경로와 이미지 경로를 설정합니다. MODEL_PATH = 'yolov8m_trained.pt' # 모델 가중치 파일의 경로를 설정하세요. IMAGE_PATH = 'image.jpg' # 예측을 원하는 이미지 파일의 경로를 설정하세요. # YOLO 모델을 불러옵니다. model = YOLO("yolov8m.pt") model.load_state_dict(torch.load(MODEL_PATH)) model.eval() 이런식으로 모델을 예측하는 용도로만 사용하고 싶은데 자꾸 모델의 구조가 다르다고 오류가 나는데 어떻게 해야할까요? ㅠㅠ

개발자

#python

#yolo

답변 1

댓글 0

추천해요 1

조회 610

useState에서 previous state인자를 사용하는 방법과 이전 값을 spread해서 사용하는 방법중 어떤 방법을 사용해야 할지 고민입니다

const [imageArray, setImageArray] = useState([]); 혹시 어떤 배열안에 있는 객체요소 state변경을 할때, setState 인자인 previous state를 받아서 수정하는게 나은가요? 예) setImageArray((prev)=> [ …prev, {something}]) 아니면 spread로 새로운 배열로 복사해서 이것을 수정하고 setState에 넣는게 나은가요? 예) const copiedArray = […imageArray]; copiedArray. something something 작업 setImageArray(copiedArray);

개발자

#usestate

#previous-state

#spread-operator

답변 1

댓글 0

조회 100

한 달 전 · @SoftyChoco 님의 새로운 답변

게시글 이미지 업로드를 구현하는데 궁금한 점이 있습니다.

velog를 참고하여 Spring + Vue를 이용하여 마크 다운 기반 게시글을 구현하고 있습니다.. 글을 쓰는 도중에 이미지를 올리면 s3에서 url를 반환하여, 이것을 통째로 Post 테이블 Content 필드에 저장하여 순서를 보장하는 식으로 진행하고 있습니다. 로직 흐름은 이렇습니다. 1. 사용자가 이미지를 올린다면, 클라이언트에서 글쓰기 버튼을 눌렀을 때 미리 만들어 놓은 UUID와 이미지를 서버로 보낸다. 2. 서버에서는 s3객체에 임시 저장 여부를 확인하는 isTemp를 태그를 넣어서 서버를 걸쳐서 S3에 쏜다. 3. S3에서 객체를 찾아서 key값과 클라이언트에서 보낸 uuid를 Image 테이블에 저장해서 Post와 간접적으로 연관 관계를 맺는다. 4. 글쓰기를 누른다면 내용과 UUID를 보내서 UUID를 Post의 primary key로 사용하고, UUID 기반으로 Image 테이블에서 key들을 갖고 와서 S3 객체의 isTemp 태그를 false로 바꾼다. 4-1 . 뒤로 가기나 임시 저장을 눌렀을 때는 isTemp를 true로 설정하고 저장한다. 5. 30일이 지날 때마다, Post에 있는 isTemp를 통해 임시 여부를 확인하여 임시 저장된 글을 삭제하고, S3에서는 수명 주기를 설정하여 태그를 기반으로 true인 이미지들을 삭제한다. 객체를 삭제하는 이유는 불필요한 데이터가 공간을 차지하는 것이 별로라고 판단했습니다. UUID는 글을 다 쓰기도 전에 서버로 쏘기 때문에, 어떤 게시글에서 쓰였는지 확인하기 위해서 사용했습니다. 성능이나 용량 면에서 안 좋다고 하지만, 이는 데이터를 넣어 놓고 조회를 하여 성능을 확인하였고 현재 프로젝트 크기를 생각했을 때 접목해도 상관없을 것 같아 넣었습니다. 하지만 이런 식으로 진행하니, 만약 사용자가 중간에 이미지 링크를 삭제한다면? 이라는 시나리오를 생각했을 때 이를 대처할 방도가 떠오르지 않습니다. 다른 분들은 어떤 식으로 처리했는지, 제가 너무 어렵게 생각하고 짜는지 궁금합니다.

개발자

#spring-boot

#s3

#게시글

답변 1

댓글 0

조회 49

캐러셀에서 다중 이미지 로드시 스켈레톤을 보여주는 방법

캐러셀 안에서 이미지 컴포넌트를 map으로 그려주고 있습니다. 이미지 컴포넌트가 로드중일 때 스켈레톤을 보여주고 싶은데 이슈가 있습니다. 이슈: 여러 이미지 컴포넌트를 그릴 때 이미지가 하나라도 로딩중이면 스켈레톤 + 컴포넌트가 동시에 보임 컴포넌트 예시 ex) const imageRef = useRef(null); const isComplete = imageRef.current?.complete; {!isComplete && <Skeleton />} <img alt={alt} src={src} ref={imageRef} /> 위와 같은 코드를 작성했는데 ref값이 세팅되기 전에 isComplete가 undefined인 순간이 있어서 그런 것 같습니다... 그래서 코드를 다음과 같이 수정했는데 스켈레톤이 무한으로 로딩되네요.. {!isComplete ? <Skeleton /> : <img alt={alt} src={src} ref={imageRef} />} 로딩시에 스켈레톤을 보여줄 수 있는 좋은 방법이 있을까요?

개발자

#react

답변 1

댓글 1

추천해요 5

조회 184

[react-native-auto-scrolling] duration 적용이 안됩니다.

https://www.npmjs.com/package/react-native-auto-scrolling 이미지 auto 스크롤을 적용하기 위해 라이브러리를 사용하고 있습니다. 위에 링크로 들어가서 readme 설명대로 이미지 컴포넌트에 duration을 적용했습니다. 그런데 에러만 발생하고 duration이 바뀌지 않네요.. <AutoScrolling style={styles.scrolling1}> <Image style={styles.image} delay={0} duration={6000} source={require("./assets/merry-christmas-png.png")} /> </AutoScrolling> 다른 라이브러리를 써야할까요? 해결책 아시는분 답변 부탁드립니다..!

개발자

#react

#react-native

#rn

답변 1

댓글 0

추천해요 3

조회 122

일 년 전 · 이지헌 님의 새로운 댓글

Next.js 이미지 최적화 방식에 대해 질문이 있습니다.

안녕하세요! Next.js 14를 사용해 프로젝트를 진행하던 중 이미지 최적화에 관해 궁금한 점이 생겨서 이 곳에 질문을 남깁니다. 프로젝트를 하며 약 500개의 이미지를 랜덤으로 추천해서 렌더링하는 기능을 구현했습니다. 현재 작업 방식은 프로젝트에서 페이지에서 이미지를 업로드 하는 기능은 필요가 없기에 MongoDB에 이미지 'URL'을 모두 저장하고 클라이언트에서 서버로 요청하면 서버에서 DB에 있는 URL을 리턴해주면 그걸 <img> 태그를 이용해서 화면에 띄우는 방식으로 구현했습니다. 하지만, 이렇게 구현하니 이미지 렌더링 속도가 조금 늦는 현상이 발생해 이를 최적화하고 싶습니다. 제가 생각했던 방법들은 다음과 같은데 어떤 방법이 좋은지, 혹은 더 나은 방법이 있는지 아시는 분이 있으면 추천해주시면 감사하겠습니다. 1. 이미지를 모두 다운받아 public 폴더에 넣고 Next/Image를 사용한다. -> 이 방법을 하려니 사진이 500개가 되고 사진마다 png,jpg 형식도 달라서 적용하는 것도 어려울 것 같고 무엇보다도 프로젝트 파일 사이즈가 커지는게 문제가 될 것 같다는 생각을 했습니다. 만약 사진이 500개가 아니라 1000개 2000개가 된다면 더더욱 그럴 것 같아서요. 이 부분에서 추가로 생각해본 방식이 파일 형식을 모두 avif로 바꾸는건데 그런 접근도 괜찮은건가요? 2. 서버에서 URL 넘어온 그대로 Next/image를 사용한다. -> 모든 파일의 url 형식이 달라서 일일이 next.config.ts에서 설정해주는 게 쉽지않을 것 같다고 생각했습니다. 그래서 모든 파일을 AWS S3에 올려놓으면 URL 주소가 같을테니 그렇게 하는 게 맞는지 궁금했습니다. 아직 제 지식이 짧아서 생각해본 방식은 위와 같은데, 추가로 좀 더 좋은 방식이나 현업에서 사용하는 방식이 있다면 알려주시면 감사하겠습니다. 긴 글 읽어주셔서 감사합니다!!!

개발자

#next.js

#리액트

#이미지최적화

#넥스트

답변 1

댓글 1

추천해요 1

조회 195

일 년 전 · 행복한 거북이 님의 새로운 댓글

소프트웨어관련학과 전공 2학년 질문드립니다. 미리 조언 감사드립니다.

안녕하십니까 저는 현재 소프트웨어관련학과에 재학중이며 2학년을 마쳤습니다. 일단 저는 대학교에서 처음으로 프로그래밍에 대해서 공부하게 되었습니다. 제가 1,2학년때 배운 것들로는 프로그래밍언어(파이썬, C언어, java) 문법, 파이썬 라이브러리(Pandas, plotlib, numpy)활용, 웹클롤링과 전처리를 통한 빅데이터 분석 팀프로젝트, 이산수학, ai수학(선형대수/최적화) , java를 이용한 안드로이드 모바일 프로그래밍 (위젯, 인텐트 등을 학습), 비주얼테크놀로지의 기반이 되는 영상처리, 컴퓨터비전의 기초 내용( image processing / feature matching / image transform, homography), 소프트웨어공학 입문( 오픈소스소프트웨어, 리눅스 학습) 정도 하였습니다. 대외활동이나 별다른 프로젝트, 블로그, 백준문제풀이등은 하지 않았습니다. 그리고 자료구조와 웹기초(html,css,javascript )관련해서는 2학년때 배우지만 수강신청을 하지 못하여 배우지 못하였으며, 알고리즘은 배우지 않는 것으로 보입니다. 제가 5월 말에 군입영을 준비하고 있는 입장에서 시간이 너무 많이 남았으며 5월까지 전공이나 진로관련하여 아무것도 하지 않고 보내기에는 시간이 너무 아깝다는 생각이 들어서, 뭐라도 해야지 하는 심정으로 현재 자료구조와 웹기초에 대해서 공부를 하고자 하는데요, 자료구조, 알고리즘 공부는 do it자료구조,알고리즘 자바나 다른 책을 이용하거나, 웹기초는 패스트캠퍼스의 '프론트엔드웹 개발의 모든것 초격차 패키지' 강의, java 백엔드는 '시그니처 백엔드 Path 초격차 패키지 Online.'강의를 수강하고자 합니다(사실 강의를 먼저 듣는게 맞는 지는 모르겠는데 이벤트에 혹해서 일단 결제는 했습니다. doit이나 혼공시리즈등의 책으로 먼저 공부한후 강의를 수강하는게 맞을 까요?) 아니면 현재까지 배운것들을 복습하면서 관심이 생기는 부분을 찾는게 맞을까요? 나중에 개발자로서 취업을 하거나 포트폴리오를 작성할때 조금이나마 도움을 받을 수 있는 활동이나 이외에도 개발자가 되기 위한 공부방법, 이 시간을 어떻게 보내면 좋을지 등 여러 의견 남겨주시면 감사하겠습니다. 다른 분들은 혹시 이렇게 남는 시간을 어떻게 보냈는지 궁금하고 남는 시간을 어떻게 하면 조금 더 의미있게 보낼까 고민하다가 혼자 고민하는 것은 너무 답답하다 싶어서 이렇게 질문드립니다....글이 깔끔하지 않은점 죄송합니다...

개발자

#진로

답변 1

댓글 2

추천해요 2

조회 252

jenkins 구축 환경 문의

안녕하세요? 현재 jenkins를 운영할 환경을 Docker Image로 만들어, AWS의 ECS나 EKS에 진행 하려 하는데 궁금한 점 있습니다. jenkins의 경우 secret key나 기타 환경 변수의 파일을 보안상의 이유로 외부 Volume을 mount하여 관리 하는 것으로 알고 있습니다. 또한 Docker의 권고 사항으로 인하여 Docke in Docker 가 아닌 Docker out Docker 형태로 Host의 docker.socket을 사용 해야한다고도 알고는 있습니다. 그럼 여기서 질뮨 1. 보통 CI/CD 툴중 jenkins를 활용 하시는 분들은 해당 툴의 구축 환경을 serverless 형태가 아닌 native 인스턴스에 구축 하시나요? 2. ecs 혹은 eks 서비스에서는 별도의 mount volume을 활용 해야 할거 같긴한데... 관리와 이슈에 대한 포인트가 발생 할 확률이 큰가요? (특히나 Docker out Docker 형태일 경우 mount volume에는 docker socket이 없는데... docker의 권고를 무시해야하는 건지...) 궁금합니다.

개발자

#jenkins

#docker

#aws

#ci/cd

답변 1

댓글 0

조회 148

2년 전 · 손유승 님의 새로운 답변

img태그에 alt는 왜 넣어야 하나요?

초보 코린이 프론트엔드 개발자 입니다. img 태그를 사용할 때 alt 속성을 넣지 않으면 아래와 같은 경고가 나오는데요 img elements must have an alt prop, either with meaningful text, or an empty string for decorative images. 왜 alt속성을 넣어줘야 하나요? 어차피 안보이는거... 고수님들 부탁드립니다.

개발자

#html

#img

#alt

답변 5

댓글 2

추천해요 3

조회 1,497

Next Image 쓰면 Invalid src prop 에러가 떠요

제곧내에요. Next Image 컴포넌트를 쓰려고 하는데, Error: Invalid src prop (https://images.unsplash.com/xxxxxx) on `next/image`, hostname "images.unsplash.com" is not configured under images in your `next.config.js` 이런 에러가 뜨면서 이미지 로드가 안됩니다. 혹시 해결 방법을 아시는 분 있나요?

개발자

#next.js

답변 1

댓글 1

추천해요 1

조회 488

일 년 전 · 박해인 님의 질문

Streamli app Azure에 배포시.

Python Streamlit으로 앱을 하나 작성 했고 Docker image로 빌드해서 azure container repository에 푸쉬 했습니다. 그리고 이미지를 기반으로 app service를 띄웠는데요. 로컬에서는 아무 문제 없이 작동이 되는데 리모트로 올라가니 streamlit cookie manager 및 feedback component를 로딩하질 못 합니다. (사실 쿠키 매니저는 설치한 적이 없어서 왜 문제가 되는지 더더욱 잘 모르겠네요) 에러 문구에는 네트워크 레이턴시나 프록시 이슈로 컴퍼넌트를 로딩 못 하는 걸수 있다 라고 하는데 혹시 관련해서 비슷한 이슈 해결하신분 계실까요?

개발자

#streamlit

#azure

#docker

#appservice

답변 0

댓글 0

조회 72

일 년 전 · 조용구 님의 새로운 답변

React json load error

Data.json을 아래와 같이 설정하고 [ {"id": 1, "name": "kim", "age": 30}, {"id": 2, "name": "lee", "age": 25}, {"id": 3, "name": "park", "age": 35} ] 리액트 app.js에서 json을 불러 출력하려고 하면 아래와 같은 에러가 나와요 SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON 아무리 검색해도 해결법을 못찾겠어서 글 올립니다ㅠㅠ 아래 스크립트는 app.js 작성한 내용입니다 ㅠ

개발자

#react

#json

#promise

#javascript

답변 2

댓글 0

조회 171

일 년 전 · 백승훈 님의 새로운 댓글

Nextjs를 정적 웹 호스팅(dothome)으로 배포하게 될 때 문제점

안녕하세요. 이번에 맡게된 프로젝트에서 SEO가 중요하다고 판단되어 Nextjs를 사용하여 개발하였습니다. 그런데 저희 팀이 사용하고 있는 웹 호스팅 서버가 dothome입니다. dothome은 정적 웹 사이트 호스팅 서버라고 알고 있는데, 이 서버로 호스팅하게 되면 몇 가지 문제점이 있다고 판단되어 질문을 남기게 되었습니다. 1. dothome에 배포하기 위해 정적 빌드를 하게 되면, 서버 사이드 렌더링(SSR) 기능을 사용할 수 없게 되는데, 이는 NextJS를 사용해서 얻을 수 있는 SEO 측면의 이점을 얻을 수 없게되는 건가요? 그렇게 된다면 SEO를 개선하는 방법이 있을까요? 2. Nextjs에서 제공하는<Image> 태그가 서버 측에서 이미지 최적화기능을 제공하는 것으로 알고 있는데, 정적빌드를 사용하게 되면 일반적인 img 태그와 다를 바가 없어지는 걸까요? 3. 마지막으로 Nextjs를 사용하기 위해서 웹 호스팅을 변경하는 것이 좋을지, 변경해야한다면 어떤 것을 추천하지는 시 여쭤봅니다.

개발자

#next.js

#dothome

#ssr

#seo

답변 3

댓글 3

추천해요 4

조회 1,083