>  기사  >  웹 프론트엔드  >  React.js 학습을 위한 종합 가이드

React.js 학습을 위한 종합 가이드

PHPz
PHPz원래의
2024-08-13 20:30:14688검색

A Comprehensive Guide to Learning React.js

Facebook에서 개발하고 유지 관리하는 React.js는 사용자 인터페이스, 특히 단일 페이지 애플리케이션(SPA)을 구축하는 데 가장 널리 사용되는 JavaScript 라이브러리 중 하나가 되었습니다. 유연성, 효율성 및 사용 용이성으로 잘 알려진 React는 모든 수준의 개발자를 위한 대규모 커뮤니티와 풍부한 리소스를 보유하고 있습니다. 귀하의 기술에 React를 추가하려는 초보자이든 숙련된 개발자이든 이 튜토리얼은 React.js의 기본 사항을 안내합니다.

1. React.js란 무엇인가요?

React.js는 특히 빠른 대화형 사용자 경험을 원하는 단일 페이지 애플리케이션의 사용자 인터페이스 구축에 사용되는 오픈 소스 JavaScript 라이브러리입니다. React를 사용하면 개발자는 데이터 변경에 대응하여 효율적으로 업데이트하고 렌더링할 수 있는 대규모 웹 애플리케이션을 만들 수 있습니다. 이는 구성 요소 기반이므로 UI가 구성 요소라고 하는 재사용 가능한 작은 조각으로 나누어져 있습니다.

2. React 환경 설정

코딩을 시작하기 전에 개발 환경을 설정해야 합니다. 다음 단계를 따르세요.

1단계: Node.js 및 npm 설치

  • Node.js: React의 빌드 도구에는 Node.js가 필요합니다.
  • npm: 노드 패키지 관리자(npm)는 라이브러리와 패키지를 설치하는 데 사용됩니다.

공식 홈페이지에서 Node.js를 다운로드하고 설치할 수 있습니다. npm은 Node.js와 함께 번들로 제공됩니다.

2단계: Create React 앱 설치

Facebook은 새로운 React 프로젝트를 빠르고 효율적으로 설정하는 데 도움이 되는 Create React App이라는 도구를 만들었습니다. 터미널에서 다음 명령을 실행하세요:

npx create-react-app my-app

이 명령은 React 프로젝트를 시작하는 데 필요한 모든 파일과 종속성을 포함하는 my-app이라는 새 디렉터리를 생성합니다.

3단계: 개발 서버 시작

프로젝트 디렉토리로 이동하여 개발 서버를 시작하세요.

cd my-app
npm start

이제 새로운 React 앱이 http://localhost:3000에서 실행될 것입니다.

3. React 구성 요소 이해

React는 구성요소에 관한 것입니다. React의 구성 요소는 일반적으로 HTML과 같은 일부 출력을 렌더링하는 자체 포함 모듈입니다. 구성 요소는 기능 구성 요소 또는 클래스 구성 요소로 정의할 수 있습니다.

기능적 구성요소

기능적 구성 요소는 HTML을 반환하는 간단한 JavaScript 함수입니다(JSX 사용).

예:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

클래스 구성요소

클래스 구성 요소는 구성 요소를 정의하는 더욱 강력한 방법이며 로컬 상태 및 수명 주기 메서드를 관리할 수 있게 해줍니다.

예:

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

4. JSX – 자바스크립트 XML

JSX는 HTML과 유사한 JavaScript의 구문 확장입니다. 이를 통해 JavaScript 내에서 직접 HTML을 작성할 수 있으며, 그러면 React가 실제 DOM 요소로 변환됩니다.

예:

const element = <h1>Hello, world!</h1>;

JSX를 사용하면 UI 구조를 더 쉽게 작성하고 시각화할 수 있습니다. 그러나 내부적으로 JSX는 React.createElement() 호출로 변환됩니다.

5. 주와 소품

소품

Prop("속성"의 약어)는 한 구성 요소에서 다른 구성 요소로 데이터를 전달하는 데 사용됩니다. 변경 불가능합니다. 즉, 수신 구성 요소에서 수정할 수 없습니다.

예:

function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

상태

상태는 props와 유사하지만 구성 요소 내에서 관리되며 시간이 지남에 따라 변경될 수 있습니다. 상태는 사용자 입력과 같이 구성 요소가 추적해야 하는 데이터에 사용되는 경우가 많습니다.

예:

class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  increment = () => {
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={this.increment}>Increment</button>
      </div>
    );
  }
}

6. 이벤트 처리

React의 이벤트 처리는 DOM 요소의 이벤트 처리와 유사합니다. 그러나 몇 가지 구문상의 차이점이 있습니다.

  • React 이벤트의 이름은 소문자 대신 CamelCase를 사용하여 지정됩니다.
  • JSX를 사용하면 문자열 대신 함수를 이벤트 핸들러로 전달합니다.

예:

function Button() {
  function handleClick() {
    alert('Button clicked!');
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}

7. 수명주기 방법

React의 클래스 구성 요소에는 구성 요소 수명 중 특정 시간에 코드를 실행할 수 있는 특별한 수명 주기 메서드가 있습니다. 여기에는 다음이 포함됩니다.

  • comComponentDidMount: 구성요소가 마운트된 후 호출됩니다.
  • comComponentDidUpdate: 구성 요소 업데이트 후에 호출됩니다.
  • comComponentWillUnmount: 구성 요소가 마운트 해제되기 전에 호출됩니다.

예:

class Timer extends React.Component {
  componentDidMount() {
    this.timerID = setInterval(
      () => this.tick(),
      1000
    );
  }

  componentWillUnmount() {
    clearInterval(this.timerID);
  }

  render() {
    return (
      <div>
        <h1>{this.state.date.toLocaleTimeString()}</h1>
      </div>
    );
  }
}

8. Conditional Rendering

In React, you can create different views depending on the state of your component.

Example:

function Greeting(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <h1>Welcome back!</h1>;
  }
  return <h1>Please sign up.</h1>;
}

9. Lists and Keys

When you need to display a list of data, React can render each item as a component. It’s important to give each item a unique "key" prop to help React identify which items have changed.

Example:

function NumberList(props) {
  const numbers = props.numbers;
  const listItems = numbers.map((number) =>
    <li key={number.toString()}>{number}</li>
  );
  return (
    <ul>{listItems}</ul>
  );
}

10. React Hooks

React Hooks allow you to use state and other React features in functional components. Some of the most commonly used hooks include:

  • useState: Allows you to add state to a functional component.
  • useEffect: Lets you perform side effects in your function components.
  • useContext: Provides a way to pass data through the component tree without having to pass props down manually at every level.

Example of useState:

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

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

11. Building and Deploying React Applications

Once your application is ready, you can build it for production. Use the following command:

npm run build

This will create an optimized production build of your React app in the build folder. You can then deploy it to any web server.

Conclusion

React.js is a powerful tool for building modern web applications. By understanding components, state management, event handling, and hooks, you can create dynamic and interactive user interfaces. This tutorial covers the basics, but React's ecosystem offers much more, including advanced state management with Redux, routing with React Router, and server-side rendering with Next.js.

As you continue your journey with React, remember to leverage the wealth of online resources, including the official React documentation, community forums, and tutorials. Happy coding!

위 내용은 React.js 학습을 위한 종합 가이드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.