반응에서 화살표 기능의 올바른 사용
리액트 사용 중JS는 Babel 및 Webpack을 사용하고 ES6 및 화살표 함수에 대해 제안된 클래스 필드를 사용합니다.화살표 함수는 컨스트럭터에서의 바인딩 동작과 마찬가지로 각각 렌더링하는 함수를 재작성하지 않음으로써 작업을 보다 효율적으로 하는 것으로 알고 있습니다.하지만 제가 그것들을 제대로 사용하고 있는지 100% 확신할 수 없습니다.다음은 내 코드를 세 개의 다른 파일로 단순화한 섹션입니다.
내 코드:
Main.js
prevItem = () => {
console.log("Div is clicked")
}
render(){
return (
<SecondClass prevItem={this.prevItem} />
)
}
세컨드 클래스.js
<ThirdClass type="prev" onClick={()=>this.props.prevItem()} />
Third Class.js
<div onClick={()=>{this.props.onClick()}}>Previous</div>
질문:.
위의 내 코드가 화살표 기능을 올바르게 사용하고 있습니까?SecondClass.js의 경우 다음 항목도 사용할 수 있었습니다.
<ThirdClass type="prev" onClick={this.props.prevItem} />
원래 함수 정의에서 ES6 화살표 기능을 사용했는데 어떤 방법이 다른가요?아니면 마지막 div까지 화살표 구문을 사용해야 하나요?
화살표 함수는 참조할 때마다 함수를 다시 만들지 않음으로써 작업을 보다 효율적으로 수행한다는 것을 알고 있습니다.
그건 사실이 아니야.
는 ""를 합니다.this
"정상" 함수가 동적으로 수행하는 사전적 방식으로 문맥을 정의합니다.이 키워드에 대해 더 자세한 정보가 필요하시면 제가 자세히 적어놨습니다.
화살표 에서는 각각 .render
.
각 에 새 됩니다.
onClick={() => {}}
세 번째 예에서는 인스턴스가 1개뿐입니다.
은 이미 합니다.
onClick={this.myHandler}
As for the benefits of arrow functions as class fields (there is a 작은 밑면, i will post it in the bottom of the answer), if you have a normal function handler that needs to access the current instance of the
class
via
this
:
myHandler(){
// this.setState(...)
}
.bind
class
.
은 '아까보다'에서 하는 입니다.constructor
밖에 안 1회차라리 1회밖에 안 가니까.
constructor(props){
super(props);
this.myHandler = this.myHandler.bind(this);
}
화살표 는, 「」는 bind
class
와 같이 은 사전 합니다.this
myHandler = () => {
// this.setState(...)
}
두 가지 방법으로 핸들러를 다음과 같이 사용합니다.
<div onClick={this.myHandler}></div>
이 접근방식을 채택하는 주된 이유는 다음과 같습니다.
<div onClick={() => this.myHandler(someParameter)}></div>
옆에 event
것, 즉 위쪽으로 합니다.
이미 설명한 바와 같이 각 렌더링에 새로운 함수 인스턴스가 생성됩니다.
(미국의)★★★★★★★★★★★★★★★★★★★)
이러한 사용 사례에 대한 실행 예:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [{ name: 'item 1', active: false }, { name: 'item 2', active: true }],
}
}
toggleITem = (itemName) => {
this.setState(prev => {
const nextState = prev.items.map(item => {
if (item.name !== itemName) return item;
return {
...item,
active: !item.active
}
});
return { items: nextState };
});
}
render() {
const { items } = this.state;
return (
<div>
{
items.map(item => {
const style = { color: item.active ? 'green' : 'red' };
return (
<div
onClick={() => this.toggleITem(item.name)}
style={style}
>
{item.name}
</div>
)})
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
더 나은 접근법은 구성요소 구성을 생성하는 것입니다.
마크업을 자할 수 컴포넌트는 , 「자 컴포넌트」를 할 수 .data
★★★★★★★★★★★★★★★★★」handler
모의의소소소소소
이 핸들러를 합니다.data
파라미터로 지정합니다.
하위 구성 요소를 사용한 실행 예제:
class Item extends React.Component {
onClick = () => {
const { onClick, name } = this.props;
onClick(name);
}
render() {
const { name, active } = this.props;
const style = { color: active ? 'green' : 'red' };
return (<div style={style} onClick={this.onClick}>{name}</div>)
}
}
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
items: [{ name: 'item 1', active: false }, { name: 'item 2', active: true }],
}
}
toggleITem = (itemName) => {
this.setState(prev => {
const nextState = prev.items.map(item => {
if (item.name !== itemName) return item;
return {
...item,
active: !item.active
}
});
return { items: nextState };
});
}
render() {
const { items } = this.state;
return (
<div>
{
items.map(item => {
return <Item {...item} onClick={this.toggleITem} />
})
}
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
[ Class ]필드 다운사이드:
말씀드렸듯이, 클래스 필드에는 작은 다운사이드가 있습니다.
가 클래스 필드에 있다는 입니다.instance
class
(일부러)
여기서 클래스 메서드와 오브젝트가 프로토타입에 부착됩니다.
따라서 이 클래스의 인스턴스가 터무니없이 많으면 퍼포먼스에 적중할 수 있습니다.
다음 코드 블록이 지정됩니다.
class MyClass {
myMethod(){}
myOtherMethod = () => {}
}
babel은 다음과 같이 변환합니다.
var _createClass = function() {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
return function(Constructor, protoProps, staticProps) {
if (protoProps) defineProperties(Constructor.prototype, protoProps);
if (staticProps) defineProperties(Constructor, staticProps);
return Constructor;
};
}();
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
var MyClass = function() {
function MyClass() {
_classCallCheck(this, MyClass);
this.myOtherMethod = function() {};
}
_createClass(MyClass, [{
key: "myMethod",
value: function myMethod() {}
}]);
return MyClass;
}();
화살표 함수는 컨스트럭터에서의 바인딩 동작과 마찬가지로 각각 렌더링하는 함수를 재작성하지 않음으로써 작업을 보다 효율적으로 하는 것으로 알고 있습니다.
그건 사실이 아니야.화살표입니다. ifArrow function
메서드에서 되는 경우 (instance)가 됩니다.everytime
)은 '하다'와 ''라고 합니다.bind
이 예시를 해 보세요.
<div onClick={()=>{this.onClick()}}>Previous</div>
이 됩니다.this.onClick
단, 아래의 경우를 고려하십시오.
onClick = () => {
console.log("Div is clicked")
}
경우 컴포넌트(React )로.An arrow function does not have its own this; the this value of the enclosing execution context is used.
수업이 인스턴스화 될 때 한 번. 해서 이렇게 하는 거랑 요.binding works is constructor
이것은 의 일부입니다.proposed class fields for arrow functions
ES6 능 es es es es
묻고 싶은 내용을 이해하려면 함수가 호출된 위치에서 컨텍스트를 얻는다는 것을 알아야 합니다.자세한 것은, 확인해 주세요.
의 경우,은 신의경신, 신은 in를 하였습니다.Arrow function
prevItem
그 때문에, 둘러싸인 React 컴포넌트의 콘텍스트를 취득합니다.
prevItem = () => {
console.log("Div is clicked")
}
render(){
return (
<SecondClass prevItem={this.prevItem} />
)
}
그 「」라고 , 「」라고 불러도, 「」라고 하는 것이 .prevItem
콘텍스트에서는, 「」를 참조해 주세요.using bind or arrow function
,prevItem
로 실행되었을 , "" " " " ", ", ",Main.js
는, 동봉되어 React합니다.하고 싶지 에 prevItem을 .
<ThirdClass type="prev" onClick={()=>this.props.prevItem()} />
그리고.
<div onClick={()=>{this.props.onClick()}}>Previous</div>
일 뿐 .SecondClass
★★★★★★★★★★★★★★★★★」ThirdClass
'화살표', '화살표', '화살표', '화살표', '화살표', '화살표', '화살표'라고 됩니다.
<ThirdClass type="prev" onClick={this.props.prevItem} />
그리고.
<div onClick={this.props.onClick}>Previous</div>
이미 부모에게 묶여 있기 때문입니다.
및 SecondClass에서해야 하는 에도 Third Class 및 Second Class 서 third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third third thirdArrow function
★★★★★★★★★★★★★★★★★」bind in render
에 대한 이 답변을 참조하십시오.
첫 번째 접근법은
<ThirdClass type="prev" onClick={()=>this.props.prevItem()} />
이 경우 ThirdClass에서 사용할 수 있는 인수를 prevItem 함수에 전달할 수 있습니다.이것은 인수를 사용하여 부모 함수를 호출하는 좋은 방법입니다.이것처럼.
<ThirdClass type="prev" onClick={()=>this.props.prevItem(firstArgument, secondArgument)} />
두 번째 접근법은
<ThirdClass type="prev" onClick={this.props.prevItem} />
이 방법에서는 ThirdClass 고유의 인수를 전달할 수 없습니다.
두 가지 기능 모두 옳습니다. 단지 사용 사례에 따라 다를 뿐입니다.es6 화살표 기능을 사용하는 두 가지 접근 방식 모두 위에서 언급한 각 시나리오에 적합합니다.
「」를 사용합니다.JavaScript
답변과 이 될 수 에 주의하십시오. 이치노
clickHandler = someData => e => this.setState({
stateKey: someData
});
, 그럼 이제 ㅇㅇㅇㅇㅇㅇㅇㅇㅇ는요.JSX
, , 라고쓸수 있습니다.
<div onClick={this.clickHandler('someData')} />
clickHandler
someData
를 e
.clickHandler
잘 된다.아, 네, 네, 네.
보다 완전하게 쓰려면 , 다음과 같이 기입해 주세요.
clickHandler = someData => () => this.setState({
stateKey: someData
});
는 없다e
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
원래 함수 정의에서 화살표를 사용하면 생성자에서 함수를 바인딩할 수 없습니다.
화살을 사용하지 않았다면...
prevItem(){
console.log("Div is clicked")
}
그런 다음 컨스트럭터를 생성하여 바인드해야 합니다.
class MyComponent extends Component {
constructor(props) {
super(props)
this.prevItem = this.prevItem.bind(this)
}
prevItem() { ... }
}
에 쉽게 사용할 수 있고, 알 가 없고, 필요가 없기 때문에 할 때 더 할 수 .그냥 작동하기 때문에 컨스트럭터가 무엇인지 이해하고 복잡함을 파고들 필요가 없기 때문입니다.this
svascript로 지정합니다.
단, 퍼포먼스를 중시하기 때문에 컨스트럭터에서 바인드하는 것이 좋습니다.bind in constructor 메서드는 렌더 메서드가 여러 번 호출되어도 함수의 단일 인스턴스를 생성하여 다시 사용합니다.
언급URL : https://stackoverflow.com/questions/48699573/correct-use-of-arrow-functions-in-react
'programing' 카테고리의 다른 글
"No capture browser" 메시지가 표시되었기 때문에 Karma가 유닛 테스트를 실행하지 않음 (0) | 2023.03.03 |
---|---|
XML 스키마(XSD)에서 Json 스키마 생성 (0) | 2023.03.03 |
ng-click angularjs 폼 검증 (0) | 2023.03.03 |
angularjs newline 필터(다른 html 없음) (0) | 2023.03.03 |
jqLite를 사용하여 클래스 이름별로 요소를 선택하는 방법은 무엇입니까? (0) | 2023.03.03 |