[英]Calling Function on onClick in React
在React的Component定義中,我要添加一個eventListener,如下所示:
/* events.js */
export function mouseyDown( event ) {
console.log( event.target );
}
/* main.js */
import mouseyDown from '../controllers/events.js';
const Topbar = React.createClass ({
callMouseyDown : function( event ) {
console.log( event.target );
mouseyDown(); // actually need to pass event to this method too
},
render : function() {
return (
<div className="tbIcon" data-action="shareSocial" onClick={ this.callMouseyDown}>G</div>
)}
});
但是,React給我一個_EventController2.default is not a function
錯誤。 我究竟做錯了什么?
Mousedown不是創建的對象的屬性,而是您導入的功能。 因此,您需要省略this
關鍵字:
onClick={mouseyDown}
此外,您需要將函數導出為默認值:
export default function mouseyDown( event ) {
console.log( event.target );
}
// ...
import mouseyDown from '../controllers/events.js';
或使用命名的導入:
export function mouseyDown( event ) {
console.log( event.target );
}
// ...
import {mouseyDown} from '../controllers/events.js';
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.