在 React 中调用 onClick 函数
Calling Function on onClick in React
在我的 React 组件定义中,我附加了一个 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';
在我的 React 组件定义中,我附加了一个 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';