Dev/React
[React] 동적 값 출력 및 활용
Ellen571
2024. 7. 5. 19:47
반응형
JSX 또는 리액트에서 동적인 값을 출력할 때는 {} 중괄호를 사용한다.
- <p>{…}</p> 태그 사이
- <img src={…} alt=””> 속성값으로
{} 중괄호 안에 자바스크립트 표현을 자유롭게 추가할 수 있다
- {1+1}
- {reactArray[0]}
태그 안에서 사용
<p> {reactDescriptions[genRandomInt(2)]} ... </p>
const reactDescriptions = ['Fundamental', 'Crucial', 'Core'];
function genRandomInt(max) {
return Math.floor(Math.random()*(max+1));
}
function Header(){
return (
<header>
<img src="src/assets/react-core-concepts.png" alt="Stylized atom" />
<h1>React Essentials</h1>
<p>
{reactDescriptions[genRandomInt(2)]} React concepts you will need for almost any app you are
going to build!
</p>
</header>
);
}
속성으로 사용
<img src={reactImg} alt="Stylized atom" />
만약 <img src="src/assets/react-core-concepts.png" />와 같이 파일을 불러오면 리액트를 배포할 때 분실될 수 있다.
- 배포 과정에서 모든 코드가 변환 및 최적화되고 함께 묶인다
- 묶여지는 과정에서 이미지가 무시되거나 유실될 수 있다
import reactImg from "./assets/react-core-concepts.png";
function Header(){
return (
<header>
<img src={reactImg} alt="Stylized atom" />
</header>
);
}
- reactImg는 이미지 경로를 포함한 자바스크립트 변수이고, 이 변수를 속성 경로에 사용한다.
- 이 때 “” 따옴표를 추가하지 않는다.
반응형