input 태그의 type 속성으로 file을 주면, 업로드를 할 수 있다.
- 파일을 상태로 관리
<div><input type=”file”/></div>
- input은
display:none
으로 가려주기
- useRef를 이용해 div를 클릭 시 input이 클릭되게 하기
- input의
onChange
속성을 통해 파일 선택 시 해당 파일을 상태로 set
const Input = styled.input` display: none ` const Upload({children, ...}) { const [file, setFile] = useState(null) const inputRef = useRef(null) const handleFileChange = (e) => { setFile(e.target.files[0]) } const handleClick = () => { inputRef.current.click() } <div onClick={handleClick}> <Input ref={inputRef} type="file" onChange={handleFileChange} ... /> {children} //Input이 안보이기 때문에 해당 자식만 보일것임 </div> }
참고) upload 컴포넌트의 자식을 받아와서, 해당 자식이 함수라면 함수를 실행하는 방식이 있다.
- 여기서는 버튼 컴포넌트를 file이 있다면 button의 텍스트를 해당 파일 이름으로, 없다면 기본 이름으로 설정하는 함수를 자식으로 설정할 수 있다
<Upload> {(file) => <button>file ? file.name : "Click me!"</button>} </Upload>
<div> <Input /> {typeof children === "function" ? children(file): children} </div>
드래그 앤 드랍으로 업로드하도록 하기
- droppable를 props로 받고, dragging을 상태로 관리

- 드래그 들어왔을 때, 떠났을 때 이벤트 함수 만들기

- 전파를 막아줘야 하는 dragover와 파일을 내려놨을 때 이벤트 함수 만들기

- 컨테이너에 콜백 함수 등록

- Input의 children을 children(file, dragging) 으로 호출하기
- Upload를 호출할 때 자식의 스타일을 dragging에 따라 바꾸도록 해서 드래그 인 할 때 시각화하기
