在React上调用onClick上的函数

时间:2016-03-02 17:05:06

标签: javascript javascript-events reactjs addeventlistener

在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错误。 我做错了什么?

1 个答案:

答案 0 :(得分:1)

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';
相关问题