0

即時通訊使用React,除了'事件'之外,我想傳遞一些參數,所以我決定使用高階函數。通過高階函數傳遞參數

但是,它不識別傳遞給高階函數的'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所報告的那樣,道具正常傳遞。上面的dispatchSelectElement通過下面的eventProps

表象部件

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,具體功能?在你向我們展示的代碼中,發生錯誤的地方確實沒有'id'變量。你爲什麼認爲它應該在那裏定義? – Bergi

+0

@Bergi''''在'path'元素的handleDispatchSelectEle函數中傳遞。然後handleDispatchSelectEle返回dispatchSelectElement函數。 – Kayote

+0

呃,我現在看到了。這不是它的工作原理。我會寫一個答案。 – Bergi

回答

1

範圍是詞彙,這意味着id將只有您handleDispatchSelectEle函數的主體(在那裏未使用)內可用。該函數返回eventProps.dispatchSelectElement無關緊要,這是一個與其自己的範圍不同的函數。

你需要寫

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