通过高阶函数传递参数
Passing Arguments Through Higher Order Function
我正在使用 React,除了 'event' 之外,我还想传递一些参数,所以我决定为此使用高阶函数。
但是,它无法识别传递给高阶函数的 '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>
);
};
Scope 是词法的,这意味着 id
仅在 handleDispatchSelectEle
函数的主体内可用(未使用的地方)。函数 returns 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>
);
}
我正在使用 React,除了 'event' 之外,我还想传递一些参数,所以我决定为此使用高阶函数。
但是,它无法识别传递给高阶函数的 '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>
);
};
Scope 是词法的,这意味着 id
仅在 handleDispatchSelectEle
函数的主体内可用(未使用的地方)。函数 returns 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>
);
}