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