초보자를 위한 React 가이드: 기본 사항 시작하기

王林
풀어 주다: 2024-08-16 06:11:03
원래의
734명이 탐색했습니다.

A Beginner’s Guide to React: Getting Started with the Basics

React는 효율성, 유연성 및 강력한 생태계로 유명한 현대 웹 개발의 초석이 되었습니다. Facebook에서 개발한 React는 개발자가 재사용 가능한 UI 구성 요소를 만들 수 있도록 하여 대화형 사용자 인터페이스 구축 프로세스를 단순화합니다.

복잡한 단일 페이지 애플리케이션을 구축하거나 단순히 웹 개발 기술을 향상시키려는 경우 React를 마스터하는 것은 귀중한 자산입니다.

이 가이드에서는 개발 환경 설정, React 기본 사항 이해, 첫 번째 구성 요소 생성 등 React를 시작하는 데 필요한 필수 개념과 단계를 안내합니다.

반응이란 무엇입니까?

React는 특히 동적이고 대화형 사용자 경험이 필요한 단일 페이지 애플리케이션에서 사용자 인터페이스를 구축하는 데 사용되는 JavaScript 라이브러리입니다. 기본적으로 React를 사용하면 개발자는 자신의 상태를 관리하는 캡슐화된 구성 요소를 구축하고 이를 구성하여 복잡한 UI를 만들 수 있습니다. React의 선언적 특성으로 인해 애플리케이션에 대해 더 쉽게 추론할 수 있으며, 구성 요소 기반 아키텍처는 재사용성과 유지 관리성을 향상합니다.

React의 간략한 역사와 진화

React는 2013년 Facebook에서 처음 출시되었으며 UI 구축에 대한 혁신적인 접근 방식으로 인해 빠르게 주목을 받았습니다. DOM을 직접 조작하는 기존 라이브러리 및 프레임워크와 달리 React는 가상 DOM 개념을 도입했습니다. 이러한 추상화를 통해 React는 변경된 UI 부분만 업데이트하여 렌더링을 최적화하여 성능을 더욱 효율적으로 만들 수 있습니다.

React는 처음부터 후크, 컨텍스트 API, 동시 렌더링과 같은 기능을 도입하면서 크게 발전했습니다. 라이브러리는 수많은 도구, 라이브러리 및 프레임워크를 기반으로 구축되어 기능을 더욱 향상시키는 활기찬 생태계를 갖추고 있습니다.

반응의 주요 특징

  1. 컴포넌트 기반 아키텍처: React의 컴포넌트 기반 접근 방식을 통해 개발자는 복잡한 UI를 자체 로직과 렌더링을 갖춘 더 작고 재사용 가능한 조각으로 나눌 수 있습니다.

  2. 가상 DOM: 가상 DOM은 실제 DOM을 메모리 내 표현한 것입니다. React는 이 가상 DOM을 사용하여 이전 상태와 비교하고 필요한 변경 사항만 적용하여 UI를 효율적으로 업데이트합니다.

  3. 선언적 구문: React의 선언적 구문을 사용하면 UI를 변경하는 방법을 지정하는 대신 특정 상태에서 UI가 어떻게 보여야 하는지 설명하여 UI를 더 쉽게 디자인할 수 있습니다.

  4. 단방향 데이터 흐름: React는 단방향 데이터 흐름을 적용합니다. 즉, 데이터가 상위 구성 요소에서 하위 구성 요소로 흐르므로 상태 변경을 더 쉽게 추적하고 관리할 수 있습니다.

개발 환경 설정

React를 시작하기 전에 HTML, CSS, JavaScript에 대한 기본적인 이해가 필요합니다. React는 이러한 기본적인 웹 기술을 기반으로 구축되므로 이러한 기술에 익숙해지면 React 개념을 더욱 효과적으로 이해하는 데 도움이 됩니다.

Node.js 및 npm 설치

React 개발에는 프로젝트 종속성을 관리하고 개발 도구를 실행하는 데 사용되는 Node.js와 npm(Node Package Manager)이 필요합니다.

Node.js 및 npm 설치 방법:

  1. Node.js 다운로드 및 설치: Node.js 공식 웹사이트로 이동하여 운영 체제에 맞는 최신 LTS(Long Term Support) 버전을 다운로드하세요. 이 설치 패키지에는 npm이 포함되어 있습니다.

  2. 설치 확인: 설치 후 터미널(또는 명령 프롬프트)을 열고 다음 명령을 실행하여 Node.js와 npm이 올바르게 설치되었는지 확인하세요.

   node -v
   npm -v
로그인 후 복사

Node.js와 npm의 버전 번호가 모두 표시되어 설치에 성공했음을 확인할 수 있습니다.

반응 애플리케이션 만들기

React를 시작하는 가장 쉬운 방법은 합리적인 기본 구성으로 새 React 프로젝트를 설정하는 create-react-app 도구를 사용하는 것입니다.

새 React 프로젝트 초기화를 위한 단계별 가이드:

  1. 전역적으로 create-react-app 설치: 터미널을 열고 다음을 실행합니다.
   npx create-react-app my-app
로그인 후 복사

my-app을 원하는 프로젝트 이름으로 바꾸세요. 이 명령은 주어진 이름으로 새 디렉토리를 생성하고 그 안에 React 프로젝트를 설정합니다.

  1. Navigate to Your Project Directory:
   cd my-app
로그인 후 복사
  1. Start the Development Server:
   npm start
로그인 후 복사

This command runs the development server and opens your new React application in your default web browser. You should see a default React welcome page, indicating that everything is set up correctly.

Understanding React Basics

Components are the building blocks of a React application. They encapsulate UI elements and logic, making it easier to manage and reuse code. Components can be classified into two types:

  1. Functional Components: These are JavaScript functions that return React elements. They are often used for simple, stateless components.

Example:

   function Welcome(props) {
     return <h1>Hello, {props.name}</h1>;
   }
로그인 후 복사
  1. Class Components: These are ES6 classes that extend React.Component and include a render method. They are used for more complex components with local state and lifecycle methods.

Example:

   class Welcome extends React.Component {
     render() {
       return <h1>Hello, {this.props.name}</h1>;
     }
   }
로그인 후 복사

JSX (JavaScript XML)

JSX is a syntax extension for JavaScript that allows you to write HTML-like code within JavaScript. It makes it easier to create React elements and components.

How JSX is Transformed into JavaScript:

JSX is not valid JavaScript by itself. During the build process, a tool like Babel transforms JSX into regular JavaScript. For example:

JSX:

const element = <h1>Hello, world!</h1>;
로그인 후 복사

Transformed JavaScript:

const element = React.createElement('h1', null, 'Hello, world!');
로그인 후 복사

Props (Properties)

Props are used to pass data from a parent component to a child component. They are read-only and help make components reusable.

Example of Passing Props to a Component:

function Greeting(props) {
  return <p>Welcome, {props.username}!</p>;
}

function App() {
  return <Greeting username="Alice" />;
}
로그인 후 복사

In this example, the Greeting component receives a username prop from the App component and displays it.

State

State allows components to manage their own data and react to user interactions. In functional components, the useState hook is used to manage state.

Introduction to the useState Hook:

The useState hook is a function that returns an array with two elements: the current state value and a function to update it.

Example of State Management Using useState:

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}
로그인 후 복사

In this example, the Counter component maintains a count state. Clicking the button updates the state, and the UI reflects the new count value.

Building Your First React Component

Let’s create a simple functional component to display a greeting message.

Step-by-Step Example:

  1. Create a New File: In the src directory of your project, create a file named Greeting.js.

  2. Define the Component:

   import React from 'react';

   function Greeting() {
     return <h1>Hello, React!</h1>;
   }

   export default Greeting;
로그인 후 복사
  1. Render the Component: Open src/App.js and render the Greeting component.
   import React from 'react';
   import Greeting from './Greeting';

   function App() {
     return (
       <div className="App">
         <Greeting />
       </div>
     );
   }

   export default App;
로그인 후 복사

Adding Basic Styles

You can style your components using inline styles or external CSS files. Here’s how to add basic styles:

  1. Inline Styles:
   function StyledGreeting() {
     const style = {
       color: 'blue',
       textAlign: 'center'
     };

     return <h1 style={style}>Hello, styled React!</h1>;
   }
로그인 후 복사
  1. External CSS: Create a CSS file (Greeting.css) in the src directory.
   .greeting {
     color: green;
     text-align: center;
   }
로그인 후 복사

Import the CSS file in Greeting.js and apply the class:

   import React from 'react';
   import './Greeting.css';

   function Greeting() {
     return <h1 className="greeting">Hello, styled React!</h1>;
   }

   export default Greeting;
로그인 후 복사

Conclusion

React is a powerful library that enables developers to build dynamic and interactive user interfaces efficiently. In this guide, we covered the basics of React, including its core concepts, setting up the development environment, understanding components, JSX, props, and state, and building your first component. We also explored styling options to enhance your components.

위 내용은 초보자를 위한 React 가이드: 기본 사항 시작하기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!