[React]데이터 바인딩(import/export)
import & export
긴 코드를 관리하기 위해서 코드를 각각 다른 파일로 분리하여 가져와서 사용할 수 있게 만들 수 있다.
파일 내보내기(export)
export default 변수명
data.js
var name = "Kim";
export default name
주의점
- 보통 파일의 가장 마지막에 적는 코드이다.
- 두 개의 변수를 동시에 export 할 경우
export { 변수1, 변수2 }
,import { 변수1, 변수2 } from 경로
파일 가져오기(import)
import 변수명 from 경로
App.js
import name from "./data.js";
function App() {
return (
{name}
);
}
import 한 파일 state에 담기
data.js
/* eslint-disable import/no-anonymous-default-export */
export default [
{
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
}
]
App.js
import Data from './data';
function App() {
let [shoes, shoes변경] = useState([Data]);
return (
)
}
import한 데이터 바인딩
import Data from './data';
function App() {
let [shoes, shoes변경] = useState([Data]);
return (
<div className="container">
<div className="row">
<div className="col-md-4">
<img src="https://codingapple1.github.io/shop/shoes1.jpg" width="100%" alt="이미지1"/>
<h4>{shoes[0].title}</h4>
<p>{shoes[0].content}</p>
<p>₩{shoes[0].price}</p>
</div>
<div className="col-md-4">
<img src="https://codingapple1.github.io/shop/shoes2.jpg" width="100%" alt="이미지2" />
<h4>{shoes[1].title}</h4>
<p>{shoes[1].content}</p>
<p>₩{shoes[1].price}</p>
</div>
<div className="col-md-4">
<img src="https://codingapple1.github.io/shop/shoes3.jpg" width="100%" alt="이미지3" />
<h4>{shoes[2].title}</h4>
<p>{shoes[2].content}</p>
<p>₩{shoes[2].price}</p>
</div>
</div>
</div>
)
}
컴포넌트화
App.js
...
// 부모 컴포넌트의 state 값을 전달.
<div className="container">
<div className="row">
<Card shoes={shoes[0]}/>
<Card shoes={shoes[1]}/>
<Card shoes={shoes[2]}/>
</div>
</div>
</div>
)
}
// 반복되는 UI 컴포넌트화.
function Card(props){
return(
<div className="col-md-4">
<img src={"https://codingapple1.github.io/shop/shoes"+(props.shoes.id+1)+".jpg"} width="100%" alt="이미지1"/>
<h4>{props.shoes.title}</h4>
<p>{props.shoes.content}</p>
<p>{props.shoes.price}</p>
</div>
)
}
반복문
App.js
...
<div className="container">
<div className="row">
{
shoes.map((a,i)=>{ // a : shoes 배열 안의 각각의 데이터
return <Card shoes={shoes[i]} i={i} key={i} /> // shoes와 i를 props로 전송
})
}
</div>
</div>
</div>
)
}
function Card(props){
return(
<div className="col-md-4">
<img src={"https://codingapple1.github.io/shop/shoes"+(props.i+1)+".jpg"} width="100%" alt="이미지1"/>
<h4>{props.shoes.title}</h4>
<p>{props.shoes.content}</p>
<p>{props.shoes.price}</p>
</div>
)
}
결과 화면
