TechScribe Notes
[코딩애플;React]import/export/map/컴포넌트만들기/데이터바인딩 본문
1.export default/ import 문법
:state에 보관하기 힘든 너무 긴 데이터는 export default/ import 문법을 이용하여 따로 저장하여 가져오는 것이 편리함.
(서버에서 가져올 때에도 동일)
따로 data.js(가명)에 아래와 같이 입력해주고
let data = [
{
id : 0,
title : "White and Black",
content : "Born in France",
price : 120000
},
{
id : 1,
title : "Red Knit",
content : "Born in Seoul",
price : 110000
},
{
id : 2,
title : "Grey Yordan",
content : "Born in the States",
price : 130000
}
] ;
export default data
가지고오고 싶은 파일에 import로 불러오고 useState로 저장해주면 됨
import data from './data.js'
function App() {
let [shoes] =useState(data)
-변수,함수,자료형 전부 export 가능함
-파일마다 export default 키워드는 하나만 사용가능
-파일 경로는 ./ 부터 시작해야 함.
2.export{ } / import { }문법
:여러개의 변수를 내보내고 싶을 때
data.js에 아래와 같이 변수를 작성후 내보냄
var name1 = 'Kim';
var name2 = 'Park';
export { name1, name2 }
가지고오고 싶은 파일에 아래와 같이 불러와서 변수,함수 등을 여러개 가져온다.
import { name1, name2 } from './data.js';
-export할 때 쓴 작명 import할 때에도 동일하게 사용할 것
📚숙제. export문법으로 가져온 데이터를 사용하여 상품목록 보여주기
-컴포넌트 생성하여 props로 state에 저장된 데이터 가져오기
function Card(props){
return(
<Col>
<img src={process.env.PUBLIC_URL + `/img/shoes${props.shoes.id+1}.jpg`} width="80%" />
<h4>{props.shoes.title}</h4>
<p>{props.shoes.content}</p>
<p>{props.shoes.price}</p>
</Col>
)
}
- map함수로 데이터 길이 만큼 상품 목록 보이도록 하기
{
shoes.map(function(a,i){
return(
<Card shoes={shoes[i]}/>
)
})
}
'프론트엔드 > React' 카테고리의 다른 글
[코딩애플;React]styled-component (1) | 2024.01.15 |
---|---|
[코딩애플;React]Router (1) | 2024.01.14 |
[코딩애플;React] 이미지 넣기/ public폴더 (0) | 2024.01.13 |
[코딩애플;React] React-Bootstrap/ 새 프로젝트 생성 (0) | 2024.01.13 |
[코딩애플;React] React를 github으로 배포하기 (0) | 2024.01.13 |