iT邦幫忙

2021 iThome 鐵人賽

DAY 30
0
自我挑戰組

從零開始學習React 系列 第 30

Day30 小實作 Image Preview Box


終於完賽了,很感謝iT邦幫忙鐵人賽這個活動,讓我在30天內因為要發文而不斷的學習,原本是一個下了班就坐在電視機前面不停轉台的沙發馬鈴薯,這30天的參賽日晚上都乖乖的坐在電腦前為了發文而學習,雖然發文內容簡短技術性的內容也不夠充足,但覺得日子很充實,雖然完賽了但接下來如果有時間想再增修補足一些內容,讓文章更有實用性。也謝謝唯一的訂閱者和撥空看我文章的同好,謝謝。

圖檔選擇器,符合檔案格式” image/png", "image/jpg" ,"image/svg”會顯示圖片,圖片格式錯鋘會出現:
檔案格式錯誤,請重新選擇。

https://ithelp.ithome.com.tw/upload/images/20211014/20139800xGFldCITnl.png

https://ithelp.ithome.com.tw/upload/images/20211014/20139800p9gbWHtT5l.png

https://ithelp.ithome.com.tw/upload/images/20211014/20139800roucnGvQN0.png

import React,{useState} from 'react';
import './App.css';

const App = () => {
  const [imgView,setimgView]= useState(null);
  const [error, setError] = useState(false);
  const handleImageChange = (ele) => {
    setError(false);
    const selected = ele.target.files[0];
    const ALLOWED_TYPES = ["image/png", "image/jpg" ,"image/svg"];
    if(selected && ALLOWED_TYPES.includes(selected.type)){
      let reader = new FileReader();
      reader.onloadend =()=>{
         setimgView(reader.result);
      }
      reader.readAsDataURL(selected);
    }else{
      setError(true);      
    }
  }

  return (
    <div className="main">    
     <div className="container">
     <h1>Image Preview Box</h1>
       {error && <p className="errorMsg">檔案格式錯誤,請重新選擇</p>}
       <div 
       className="imgView"
       style={{background:imgView ? `url("${imgView}") no-repeat center/cover` : "#9A9483"}}
       >
         {!imgView && (
           <>
          <p>Add an image</p>
          <label htmlFor = "fileUpload" className="customFileUpload">
          請選擇圖檔</label>       
          <input type="file" id="fileUpload" onChange={handleImageChange} />
          <span>(png, jpg or svg)</span>
          </>
         )}
       </div>
       {imgView && <button onClick={()=>setimgView(null)}>Remove Image</button>}
      </div>
    </div>
  )
}

export default App;

上一篇
Day29 React - Styled-Components
系列文
從零開始學習React 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言