0

Im React를 사용하여 'event'외에도 몇 가지 인수를 전달하고자하므로이 함수에 Higher Order 함수를 사용하기로했습니다.Higher Order Function을 통한 인수 전달

그러나 Higher Order 함수에 전달 된 'id'는 인식하지 못합니다.

컨테이너 컴포넌트

... 
const mapDispatchToProps = (dispatch) => { 
    return({ 
     dispatchSelectElement : function(e){ 
      console.log(id); // Error: id is not defined. 
      dispatch(selectElement(id, type, pos)); 
     }, 
     ... 
    }); 
}; 
const C_ElementParent = connect(mapStateToProps, mapDispatchToProps)(ElementParent); 

용기 요소 & 아래 프리젠 테이션 컴포넌트 사이에있는 다른 구성 요소가있다. 소품은 console.log에서보고 한대로 잘 전달되고 있습니다. 위의 dispatchSelectElementeventProps 아래에 전달됩니다.

표현상 성분

const Element = ({ id, colorName, eleProps, eventProps }) => { 
    let handleDispatchSelectEle = function(id){ 
     return eventProps.dispatchSelectElement; 
    } 
    return(
     <g id = { id }> 
      <path onMouseDown = { eleProps.get("mouseDown") && handleDispatchSelectEle(id)} /> 
     </g> 
    ); 
}; 
+0

를 작성해야합니까? 여러분이 우리에게 보여준 코드에서 에러가 발생하는 지점에 실제로 'id'변수가 없습니다. 왜 거기에 정의되어야한다고 생각 했습니까? – Bergi

+0

@Bergi'id'는'path' 엘리먼트 내의 handleDispatchSelectEle 함수에 전달됩니다. 그런 다음 handleDispatchSelectEle은 dispatchSelectElement 함수를 반환합니다. – Kayote

+0

어, 이제 알겠습니다. 그것이 작동하는 방식이 아닙니다. 나는 대답을 쓸 것이다. – Bergi

답변

1

범위 id이 (가 사용되지 않는다)하여 handleDispatchSelectEle 함수 본체 내부에서만 사용할 것 즉, 어휘이다. 함수가 eventProps.dispatchSelectElement을 반환한다는 것은 중요하지 않습니다. 이는 해당 범위가있는 별개의 함수입니다. 당신이 어떤 기능에 ID를 전달하는 경우

당신은

function mapDispatchToProps(dispatch) { 
    return { 
     handleDispatchSelectElement: (id) => (e) => { 
//         ^from here on, `id` is in scope 
      console.log(id); // Error: id is not defined. 
      dispatch(selectElement(id, type, pos)); 
     }, 
     … 
    }; 
} 

function Element({ id, colorName, eleProps, eventProps }) { 
    // pass the id here, to create a function: 
    const dispatchSelectEle = eventProps.handleDispatchSelectElement(id); 
    return (
     <g id={id}> 
      <path onMouseDown={ eleProps.get("mouseDown") && dispatchSelectEle } /> 
     </g> 
    ); 
} 
+0

감사합니다. 나는 어휘 범위를 이해하고 있다고 생각했다. 그것의 개정에 등을 맞댄. – Kayote

관련 문제