-
Use this in a ComponentStudy/React 2020. 5. 26. 19:01
Use this in a Component
this 단어는 리엑트에서 많이 사용된다!
당신은 특히 컴포넌트 클래스 선언의 body 내부에서 this를 아마도 보았을 것이다.
예를 들어보자.
class IceCreamGuy extends React.Component { get food() { return 'ice cream'; } render() { return <h1>I like {this.food}.</h1>; } }
코드에서, this는 무엇을 의미할까?
한번 예측해보고, 답을 보기 위해 스크롤을 내려보자.
간단한 답은 this는 IceCreamGuy의 인스턴스를 가리킨다는 것이다.
덜 간단한 대답은 this는 this의 감싸진 method (이 경우엔 .render())가 호출되는 객체를 가리킨다.
이 객체가 IceCreamGuy의 한 인스턴스가 되는 것은 거의 불가피하지만, 기술적으로는 이것은 다른 것이 될 수 있다.
본 과정의 모든 예시에서와 같이, this가 당신의 클래스의 인스턴스를 가리킨다고 가정해보자.
IceCreamGuy는 두 method를 가진다. : .food와 .render()
this가 IceCreamGuy의 인스턴스를 평가할것이기 때문에, this.food는 IceCreamGuy의
.food method의 호출에 평가할 것이다.
this는 IceCreamGuy의 인스턴스를 평가할 것이기 때문에, this.food는 IceCreamGuy의 food method 호출을 반영할 것이다. 이 메소드는 'ice cream' string을 반영할 것이다.
왜 this.food 이후에 ()는 필요하지 않을까?
this.food()가 되면 안되는 것일까?
.food 가 getter메소드 이기 때문에 당신은 괄호가 필요치 않다.
당신은 클래스 선언 body안에 get으로부터 this를 부를 수 있다.
getter 메소드에 대한 react-specific은 없다.
그러나 리엑트에서 당신은 이런방식으로 사용되는 this를 끊임없이 볼 것이다.
자바스크립트에서 this는 어려운 개념일 수 있다.
여기 js this를 이해하기 위한 좋은 자료가 있다. understanding this in JavaScript.
Gentle Explanation of "this" in JavaScript
The value of this keyword in JavaScript is determined by how the function is called. My guide will help you effortlessly understand this.
dmitripavlutin.com
import React from 'react'; import ReactDOM from 'react-dom'; class MyName extends React.Component { // name property goes here: get name() { return 'whatever-your-name-is-goes-here'; } render() { return <h1>My name is {this.name}.</h1>; } } ReactDOM.render(<MyName />, document.getElementById('app'));
'Study > React' 카테고리의 다른 글
this.props (0) 2020.05.27 Use an Event Listener in a Component (0) 2020.05.26 Use a Conditional in a Render Function (0) 2020.05.26 Put Logic in a Render Function (0) 2020.05.26 Use a Variable Attribute in a Component (0) 2020.05.26