웹 스터디 노트-React

참고 내용은 AcWing의 웹 응용 프로그램 클래스 유인물, 과정 링크: AcWing 웹 응용 프로그램 클래스 에서 재생산되었습니다 .

1. 리액트 설정 환경

리액트 공식 홈페이지: 리액트 .

React는 사용자 인터페이스 구축을 위한 선언적이고 효율적이며 유연한 JavaScript 라이브러리입니다. React를 사용하면 일부 짧고 독립적인 코드 조각을 복잡한 UI 인터페이스로 결합할 수 있으며 이러한 코드 조각을 React 라고 합니다 components. React를 사용하면 시간이 지남에 따라 데이터가 변경되는 대규모 애플리케이션을 구축할 수 있습니다.

반응 기능:

  • 페이지를 편리하게 유지하기 위해 React는 메모리에 가상 DOM 트리를 생성합니다. Virtual DOM이는 DOM이 어떻게 생겼는지, 어떻게 표시되어야 하는지를 설명하는 React에 의해 추상화된 객체인 경량 가상 DOM입니다. 이를 사용하여 Virtual DOM실제 DOM을 업데이트하고 Virtual DOM실제 DOM의 업데이트를 관리합니다.
  • 데이터 기반: 특정 요소의 데이터가 변경되면 React는 수정할 수 있는 모든 요소를 ​​다시 수정한 다음 실제 DOM 트리와 비교하여 차이점이 있는지 확인합니다. 실제 변경 지점의 결과를 수정합니다. 메모리에서 객체를 수정하는 것이 매우 빠르기 때문에 React는 매우 효율적입니다.
  • React는 일반적으로 JS를 직접 손으로 작성하지 않고 JSX 파일을 작성하여 작성합니다.

(1) 설치 Git Bash: Windows 설치 Git 튜토리얼(2022.11.18 Git2.38.1) .

(2) 설치 NodeJS: NodeJS 설치 및 설정 .

(3) 설치 create-react-app: 를
열고 Git bash다음 명령을 실행합니다.

npm i -g create-react-app

속도가 매우 느린 경우 먼저 미러 소스를 수정한 다음 설치를 시도할 수 있습니다.

npm config set registry https://registry.npm.taobao.org
npm i -g create-react-app

설치가 완료된 후 경고가 표시되면 npm WARN deprecated [email protected]: This version of tar is no longer supported, and will not receive security updates. Please upgrade asap.먼저 업데이트를 시도할 수 있습니다 tar.

npm install -g tar

여전히 경고가 있고 프로젝트를 생성할 때 오류가 보고되는 경우(예: execution create-react-app react-app) 다음 bash: create-react-app: command not found을 사용하여 npx프로젝트를 생성합니다.

npx create-react-app my-app

또는 npm다음을 사용하여 프로젝트를 만듭니다.

npm init react-app my-app

생성 후 프로젝트 폴더를 입력하여 프로젝트를 시작합니다.

cd my-app
npm start

시작 후 효과는 다음과 같습니다( ctrl+c서비스를 중지할 수 있음).

여기에 이미지 설명 삽입

여기에 이미지 설명 삽입

(4) VS Code 플러그인 구성: Simple React Snippets, Prettier - Code formatter는
Simple React SnippetsReact 지능형 자동 완성 플러그인입니다.

여기에 이미지 설명 삽입

예를 들어 imrc완료하려면 다음 내용을 입력하십시오.

import React, {
    
     Component } from 'react';

입력하여 cc다음을 완료하십시오.

class Example extends Component {
    
    
    state = {
    
      } 
    render() {
    
     
        return ();
    }
}
 
export default Example;

Prettier - Code formatter코드 서식 지정 플러그인입니다.

여기에 이미지 설명 삽입

(5) 만들기 React App:
대상 디렉토리를 마우스 오른쪽 버튼으로 클릭하여 Git Bash를 엽니다.

여기에 이미지 설명 삽입

터미널에서 실행:

npx create-react-app react-app  # react-app是新建项目的名字,可以替换为其他名称
cd react-app
npm start  # 启动应用

성공적으로 시작되면 로컬에서 3000 포트가 열리고 페이지 효과가 위에 표시됩니다. react-app이제 VS Code를 사용하여 폴더를 엽니다 .

여기에 이미지 설명 삽입

그 중 node_modules다양한 JS 라이브러리를 유지하는데 사용되며 향후 설치되는 모든 의존성은 이 폴더에 위치하게 되며, 그 public안에 있는 index.html것이 앞으로 렌더링할 페이지이고 이 파일에는 하나만 있습니다 <div id="root"></div>. src그 안에 있는 코드는 index.js다음과 같습니다.

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(document.getElementById('root'));  // 获取div同时创建为一个React对象
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

이는 App다음에 정의되어 있습니다 App.js.

import logo from './logo.svg';
import './App.css';

function App() {
    
    
  return (
    <div className="App">
      <header className="App-header">
        <img src={
    
    logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

App구성 요소는 페이지의 특정 내용을 정의하며 JS 파일에 HTML 코드가 있음을 알 수 있으므로 이 파일은 JavaScript 기반의 XML(Extensible Markup Language)을 지원할 수 있는 JSX 파일이며 HTML은 특별한 XML도 있습니다.

JSX는 Babel 에 의해 표준 JavaScript로 컴파일되는 React의 언어입니다 .

2. ES6 문법 보충

ECMAScript 6.0의 전체 이름인 ES6은 JavaScript의 버전 표준입니다. 여기에 React에서 일반적으로 사용되는 일부 구문 설탕을 추가합니다.

(1) 함수 바인딩을 사용하여 bind()가져오기this
JavaScript에서 함수는 this정의 시점의 개체가 아니라 실행 시점의 호출자를 가리킵니다. 예를 들어:

const person = {
    
    
  name: "abc",
  talk: function() {
    
    
    console.log(this);
  }
}

person.talk();

const talk = person.talk;
talk();

작업 결과는 다음과 같습니다.

{name: 'abc', talk: f}
undefined

bind()함수에 바인딩된 this값을 사용합니다 person. 예를 들어:

const talk = person.talk.bind(person);

작업 결과는 다음과 같습니다.

{name: 'abc', talk: f}
{name: 'abc', talk: f}

(2) 화살표 함수의 약식
함수 매개변수가 하나만 있는 경우 괄호를 제거할 수 있으며 함수 본문에 return명령문이 하나만 있는 경우 return및를 {}함께 제거할 수 있습니다. 예를 들면 다음과 같습니다.

const f = (x) => {
    
    
  return x * x;
};

다음과 같음:

const f = x => x * x;

(3) 화살표 함수는 this값을 리바인딩하지 않습니다.

const person = {
    
    
  talk: function() {
    
    
    setTimeout(function() {
    
    
      console.log(this);
    }, 1000);
  }
};

person.talk();  // 输出Window
const person = {
    
    
  talk: function() {
    
    
    setTimeout(() => {
    
    
      console.log(this);
    }, 1000);
  }
};

person.talk();  // 输出 {talk: f}

(4) 사물의 해체

const person = {
    
    
  name: "abc",
  age: 18,
  height: 180,
};

const {
    
    name : new_name, age} = person;  // new_name是name的别名

(5) 배열과 객체의 확장

let a = [1, 2, 3];
let b = [...a];  // b是a的复制,和a不是一个数组,如果写let b = a则b和a是同一个数组
let c = [...a, 4, 5, 6];  // c = [1, 2, 3, 4, 5, 6]

let d = {
    
    name: "abc"};
let e = {
    
    age: 18, height: 180};
let f = {
    
    ...d, ...e, weight: 120};  // f = {name: "abc", age: 18, height: 180, weight: 120}

(6)명명된 내보내기与기본 내보내기

  • Named Exportexport: 1개 이상이 될 수 있으며 , import사용시 중괄호가 필요하고, 이름, 즉 이전에 사용한 메소드와 일치해야 합니다.
  • Default Export: 기껏해야 export중괄호 import가 필요하지 않으며 별칭을 직접 정의할 수 있습니다.

3. 구성품

(1) 프로젝트 만들기
먼저 새 프로젝트를 만듭니다 box-app.

npx create-react-app box-app
cd box-app
npm start

bootstrap라이브러리를 설치합니다 .

npm i bootstrap

bootstrap가져오기 방법:

import 'bootstrap/dist/css/bootstrap.css';

(2) 컴포넌트 생성 폴더
에 컴포넌트를 저장할 폴더를 생성 한 후, 폴더에 JSX 파일을 생성합니다 .srccomponentscomponentsbox.jsx.js.jsx

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
      } 
    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (<h1>Hello World!</h1>);
    }
}
 
export default Box;

index.js그런 다음 구성 요소를 렌더링 해야 합니다 .

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import 'bootstrap/dist/css/bootstrap.css';
import Box from './components/box';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Box />
  </React.StrictMode>
);

(3) 버튼 만들기
Component에 있는 render()함수는 return하나의 요소만 가질 수 있으므로 자식 노드의 수가 1보다 많을 때 사용하거나 <div>묶을 <React.Fragment>수 있습니다.

(4) 포함된 표현식
JSX는 {}HTML 태그에 포함된 표현식을 사용합니다.

(5) 속성 설정 JS에서는 키워드이므로
HTML 태그에서 변경해야 합니다 . CSS 속성도 수정해야 합니다. 예를 들어 로 수정하면 다른 속성도 비슷합니다.classclassclassNamebackground-colorbackgroundColor

포괄적인 예:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 0
    };

    styles = {
    
    
        width: '50px',
        height: '50px',
        backgroundColor: 'lightblue',
        color: 'white',
        textAlign: 'center',
        lineHeight: '50px',
        borderRadius: '5px'
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.styles}>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }
}
 
export default Box;

(6) 데이터 기반 스타일 변경,
예:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px'
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

(7) 목록 렌더링
함수는 목록을 렌더링하는 데 사용할 수 map있으며 각 요소는 React가 수정된 DOM 요소를 빠르게 찾을 수 있도록 고유한 속성을 가져야 합니다 key. 예를 들면 다음과 같습니다.

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1,
        colors: ['red', 'green', 'blue']
    };

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div>{
    
    this.state.x}</div>
            <button className='btn btn-primary m-2'>Left</button>
            <button className='btn btn-success m-2'>Right</button>
            {
    
    this.state.colors.map(color => (
                <div key={
    
    color}>{
    
    color}</div>
            ))}
        </React.Fragment>
        );
    }
}
 
export default Box;

(8) 조건부 렌더링은
논리적 표현의 단락 원칙을 사용합니다.

  • 같은 식에서 false 일 때 값이 반환되고 , 그렇지 않으면 expr1 && expr2이 반환됩니다.expr1expr1expr2
  • 또는 expression expr1 || expr2, expr1true 일 때 반환되는 값 expr1, 그렇지 않으면 expr2반환되는 값.

(9) 바인딩 이벤트
예를 들어, 바인딩 버튼의 클릭 이벤트를 사용할 수 있는데 onClick, 바인딩 이벤트 기능을 적절히 처리해야 한다는 점에 유의하시기 바랍니다 this.

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft() {
    
      // 如果不用箭头函数或者下面调用函数时使用bind(this)的话this会变成undefined
        console.log('click left', this);
    }

    handleClickRight = () => {
    
    
        console.log('click right', this);
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeft} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    this.handleClickRight} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }
}
 
export default Box;

(10) 상태를 수정
하려면 함수가 필요합니다 this.setState()this.setState()함수가 호출된 후 함수가 다시 호출되어 this.render()가상 DOM 트리를 수정합니다. React는 동기화되지 않은 실제 DOM 트리 노드만 수정합니다. 예를 들어:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft = () => {
    
    
        // this.state.x--;  这样写的话React不会修改前端页面的效果
        this.setState({
    
    
            x: this.state.x - 1
        });
    }

    handleClickRight = () => {
    
    
        this.setState({
    
    
            x: this.state.x + 1
        });
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeft} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    this.handleClickRight} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px',
            position: 'relative',
            left: this.state.x
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

(11) 이벤트 함수에 매개 변수를 추가하려면
임시 함수 바인딩 이벤트를 정의한 다음 함수에서 원래 함수를 호출하고 매개 변수를 전달하거나 임시 화살표 함수를 직접 사용하여 바인딩할 때 원래 매개 변수를 반환할 수 있습니다. 이벤트.함수. 예를 들어:

import React, {
    
     Component } from 'react';  // 输入imrc即可补全

class Box extends Component {
    
      // 输入cc即可补全
    state = {
    
     
        x: 1
    };

    handleClickLeft = (step) => {
    
    
        this.setState({
    
    
            x: this.state.x - step
        });
    }

    handleClickRight = (step) => {
    
    
        this.setState({
    
    
            x: this.state.x + step
        });
    }

    handleClickLeftTmp = () => {
    
    
        this.handleClickLeft(10);
    }

    render() {
    
      // Component类的函数,用来返回当前组件最后渲染的HTML结构是什么
        return (
        // HTML标签中可以使用{}写一个表达式
        <React.Fragment>
            <div style={
    
    this.getStyles()}>{
    
    this.state.x}</div>
            <button onClick={
    
    this.handleClickLeftTmp} className='btn btn-primary m-2'>Left</button>
            <button onClick={
    
    () => this.handleClickRight(10)} className='btn btn-success m-2'>Right</button>
        </React.Fragment>
        );
    }

    getStyles() {
    
    
        let styles = {
    
    
            width: '50px',
            height: '50px',
            backgroundColor: 'lightblue',
            color: 'white',
            textAlign: 'center',
            lineHeight: '50px',
            borderRadius: '5px',
            position: 'relative',
            left: this.state.x
        };

        if (this.state.x === 0) {
    
    
            styles.backgroundColor = 'orange';
        }

        return styles;
    }
}
 
export default Box;

Supongo que te gusta

Origin blog.csdn.net/m0_51755720/article/details/127922719
Recomendado
Clasificación