【问题标题】:Calling Function on onClick in React在 React 中调用 onClick 函数
【发布时间】:2016-06-15 16:29:31
【问题描述】:

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

【问题讨论】:

    标签: javascript javascript-events reactjs addeventlistener


    【解决方案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';
    

    【讨论】:

    • 谢谢,它似乎不起作用。我没有错误,什么都没有。为了清楚起见,我重命名了 onClick 函数。
    • 你是最高级别的天才。谢谢。
    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多